简体   繁体   English

从2个视图使用委托协议的合适方法是什么?

[英]What would be the appropriate way to use a delegate protocol from 2 views?

I have a view controller, which uses a delegate protocol in order to pass back an array of strings. 我有一个视图控制器,它使用委托协议来传递回字符串数组。 I now have another view controller, which I'd like to use the same protocol, but I've I use it I get a warning in Xcode Duplicate protocol definition of 'SearchDetailsDelegate' is ignored . 现在,我有另一个视图控制器,我想使用相同的协议,但是我已经使用了它,但在Xcode中,我收到一条警告,提示Duplicate protocol definition of 'SearchDetailsDelegate' is ignored

I need these two views to pass back an array for the parent view controller to parse. 我需要这两个视图来传回一个数组,以供父视图控制器解析。 What would be a more appropriate way of achieve what I need to do here? 什么是实现我在这里需要做的更合适的方法? Would key value observing be the way to go here? 观察键值会成为这里的方法吗?

You have few options: 您有几种选择:

  1. rename your protocols to be different. 重命名您的协议以使其不同。

  2. create an external protocol and adopt that protocol on each view 创建一个外部协议并在每个视图上采用该协议

  3. Add a property to your view called ParentController with a type of it's parent. 向您的视图添加一个名为ParentController的属性,该属性的类型为父级。

    @property (strong,nonatomic) ParentViewController *ParentController; @property(强,非原子)ParentViewController * ParentController;

(synthesise that off course) (合成偏离路线)

Then, in your viewController, when you instantiate the view assign the viewController as the parent 然后,在您的viewController中,当实例化视图时,将viewController作为父对象

YourView *childView  = [[YourView alloc]init];
childView.parentController = self;

Now you can add a method in your viewController that can receive the strings array 现在,您可以在viewController中添加一个可以接收字符串数组的方法

-(void)setStringsArray:(NSArray*)arr{
     //do what ever you need with the array
     //don't forget to add this method to your .h file so it will be visible
}

Lastly send the strings array from the view: [self.parentController setStringsArray:yourArray]; 最后从视图发送字符串数组:[self.parentController setStringsArray:yourArray];

BTW if you want to know what view send the array you can: 顺便说一句,如果您想知道哪个视图发送了数组,您可以:

-(void)setStringsArray:(NSArray*)arr fromView:(UIView*)senderView{
     //do what ever you need with the array
     //don't forget to add this method to your .h file so it will be visible
} 

and use 和使用

    [self.parentController setStringsArray:yourArray fromView:self];

BTW 2 an other option will be to use notifications. 顺便说一句2 ,另一个选择是使用通知。

在单独的.h文件(目标c协议的新文件)中定义协议,然后将其包含在所需的视图控制器中。不建议在两个不同的视图控制器中重新定义相同的协议

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM