所有这些都是我的第一篇文章,我将尽力做到尽可能精确。我已经阅读了许多有关iOS协议(protocol)/委托(delegate)实现的文章,但是所有示例均失败。
说吧
我有A和B Controller ,想将数据从A发送到B。

    @protocol exampleprot <NSObject>
@required
-(void) exampledmethod:(NSString *) e1;
@end

@interface ViewController
{
__weak id <exampleprot> delegate
}

--

在某些过程中
我努力插入
[delegate  examplemethod:@"test"]

h
@interface test2 : UiViewcontroller <exampleprot>

并在B.m中实现方法-(void)exampledmethod:(NSString *)e1;

所以我做错了吗?

最佳答案

基本上,这是自定义委托(delegate)的示例,它用于将消息从一个类发送到另一个类。因此,要在另一个类中发送消息,您需要首先设置委托(delegate),然后在另一个类中也遵循协议(protocol)。下面是示例:
B.h

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

B.m类中
- (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];
}

A.h类中
@interface AWindowController : NSWindowController<sampleDelegate> //conforming to the protocol

A.m类中
 //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

    }

10-05 20:24
查看更多