iOS Protocol / Delegate confusion?

Basically this is the example of custom delegates and it is used for sending messages from one class to another. So for sending message in another class you need to first set the delegate and then conforming the protocol in another class as well. Below is the example:-

B.h class

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

In B.m class

- (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];
}

In A.h class

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

In A.m class

 //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 

    }

Leave a Comment