iOS协议/委托混淆?

这一切都是我的第一篇文章,我会尽可能地精确。 我已经阅读了许多关于iOS的协议/委托实现的文章,但是所有的例子都失败了。 假设我有A和B控制器,并希望从A发送数据到BAh

@protocol exampleprot <NSObject> @required -(void) exampledmethod:(NSString *) e1; @end @interface ViewController { __weak id <exampleprot> delegate } 

– 我正在尝试一些程序

 [delegate examplemethod:@"test"] 

BH

 @interface test2 : UiViewcontroller <exampleprot> 

并在Bm中实现方法 – (void)exampledmethod:(NSString *)e1;


所以我做错了什么?

基本上这是自定义委托的例子,它用于从一个类发送消息到另一个。 因此,要在另一个类中发送消息,您需要首先设置委托,然后将该协议在另一个类中一致。 下面是例子:

Bhclass

 @protocol sampleDelegate <NSObject> @required -(NSString *)getDataValue; @end @interface BWindowController : NSWindowController { id<sampleDelegate>delegate; } @property(nonatomic,assign)id<sampleDelegate>delegate; @end 

Bmclass

 - (void)windowDidLoad { //below only calling the method but it is impelmented in AwindowController class if([[self delegate]respondsToSelector:@selector(getDataValue)]){ NSString *str= [[self delegate]getDataValue]; NSLog(@"Recieved=%@",str); } [super windowDidLoad]; } 

Ah

 @interface AWindowController : NSWindowController<sampleDelegate> //conforming to the protocol 

在上课

  //Implementing the protocol method -(NSString*)getDataValue { NSLog(@"recieved"); return @"recieved"; } //In this method setting delegate AWindowController to BWindowController -(void)yourmethod { BWindowController *b=[[BWindowController alloc]init]; b.delegate=self; //here setting the delegate } 

如果你想从A发送数据到B,那么你应该在返回typesB中定义一个委托。 在B中,会有委托声明:

 @protocol example <NSObject> @required -(NSString *) exampleMethod; @end 

然后在A中实现这个方法。 在上午,你需要有

 -(NSString *) exampleMethod:(NSString *) e1 { // Implementation of this delegate method return self.stringYouWantToPassToB } 

然后在B中,你所要做的就是使用这个委托从A得到你想要的。在Bm中,你有

 - (void)methodInB { // Get string from delegate self.string = [self.delegate exampleMethod]; } 

您需要将视图控制器的委托属性设置为您要将数据发送到的位置=视图控制器到您要发送数据的位置。 我认为侯赛因的答案是正确的。 你只需要检查你是否正确的做法。