Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
397 views
in Technique[技术] by (71.8m points)

objective c - iOS Protocol / Delegate confusion?

All this is my first post and I will try to be as precise as possible. I have read numerous articles about protocol / delegate implementation for iOS but all examples failed. Let say I have A and B controller and want to send data from A to B. A.h

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

@interface ViewController
{
__weak id <exampleprot> delegate
}

-- A.m in some procedure I try to push

[delegate  examplemethod:@"test"]

B.h

@interface test2 : UiViewcontroller <exampleprot>

and in B.m implement method -(void) exampledmethod:(NSString *) e1;


so what I am doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 

    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...