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?
Protocol: A set of methods that would be implemented by the class which conforms to that protocol. Delegate: The reference to that class which conforms to the protocol and will adhere to implement methods defined in the protocol.
Protocol is a set of methods (either optional or required) that would be implemented by the class which conforms to that protocol. While, delegate is the reference to that class which conforms to that protocol and will adhere to implement methods defined in protocol.
In Swift, declaring a delegate property is just like declaring any other property and you specify the protocol name as the type of the property. You may notice the question mark syntax which indicates that it's a property with an optional value (there may or may not be an object assigned to it).
If there was no protocol, you cannot make sure that delegate methods are implemented in a way you require them to be. Even if you use a class instead of a protocol, there can be problems regarding multiple inheritance and the implementation becomes difficult.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With