Delegate)Is an object. The object of another class requires the delegate object to perform some of its operations.
Creating an "NSObject" category is called creatingInformal agreement.
Any class object that implements the method in the "NSObject" category can be a delegate object. Because all
All classes are subclasses of NSObject.
When you want to send a message to the delegate object, it is best to check whether the object understands the message you want to send.
If ([delegate respondsToSelector: @ selector (...)]
{
[Delegate...];
}
Formal Agreement: Define a formal protocol by listing a group of method names in the @ protocol section. It is listed after the class name in the @ interface declaration
The name of the Protocol enclosed in angle brackets. The protocol can be used for the object. When an object uses a protocol, it promises to fulfill every requirement listed in the Protocol.
Implementation Method. If you do not implement it, the compiler will give a warning to help you fulfill your promise.
When you use a protocol, it is best to display the statement, not just the method of implementing the Protocol (although this can be done ).
In the following example, the Protocol FooDelegate is not declared, but the Protocol method (void) fun is implemented. This can work even though,
But this is not a good programming habit. (The Declaration of Temp should be changed to @ interface Temp: NSObject <FooDelegate>)
We should always specify the Protocol we use in class declaration, which clearly expresses our intention. This is also the reason for the formal agreement. Otherwise
Informal agreements are satisfied.
/********************************************** Foo.h***********************************************/#import <Foundation/Foundation.h>@interface Foo : NSObject{ NSInteger _t;}@property NSInteger t;@property (nonatomic, strong) id delegate;-(void) notify;@end@protocol FooDelegate-(void)fun;@end/********************************************** Foo.m***********************************************/#import "Foo.h"@implementation Foo@synthesize delegate;-(void)setT:(NSInteger)newt{ self.t = newt;}-(NSInteger)t{ NSLog(@"getter"); return self.t;}-(void) notify{ NSLog(@"notify..."); if ([delegate respondsToSelector:@selector(fun)]) { [delegate fun]; }}@end/********************************************** Temp.h***********************************************/#import <Foundation/Foundation.h>@interface Temp : NSObject@end/********************************************** Temp.m***********************************************/#import "Temp.h"@implementation Temp-(void) fun{ NSLog(@"Temp fun");}@end/********************************************** main.m***********************************************/#import <Foundation/Foundation.h>#import "Foo.h"#import "Temp.h"int main (int argc, const char * argv[]){ @autoreleasepool { Foo *ob = [[Foo alloc] init]; Temp *t = [[Temp alloc] init]; ob.delegate = t; [ob notify]; } return 0;}