Reputation: 83
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?
Upvotes: 5
Views: 9207
Reputation: 15015
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
}
Upvotes: 8
Reputation: 68
You need to set the delegate property of the view controller from where you want to send the data = the view controller to where you want to send the data. I think Hussain's answer is correct. You just need to check if you are doing it the correct way.
Upvotes: 0
Reputation: 336
If you want to send data from A to B, then you should define a delegate in B with return type. In B, there will be delegate declaration:
@protocol example <NSObject>
@required
-(NSString *) exampleMethod;
@end
Then in A, implement this method. In A.m, you need to have
-(NSString *) exampleMethod:(NSString *) e1 {
// Implementation of this delegate method
return self.stringYouWantToPassToB
}
Then in B, all you need to do is use that delegate to get what you want from A. In B.m, you have
- (void)methodInB {
// Get string from delegate
self.string = [self.delegate exampleMethod];
}
Upvotes: 0