总结delegate和protocol关系拿来给大家分享一下:
- 把自己不想干的一些事情(洗衣做饭)找个助手来帮助你做,而你要的这个助手得有一定的能力,不是任何一个人都可以的,所以你就得有个招聘要求。协议(protocol)就类似于你的招聘要求,你找到的助手就是代理(delegate)。 这样就有了我.delegate = 助手;好了这样以后再有洗衣做饭的活直接找助手做就可以了。
协议不是类,以@protocol关键字声明, 协议有两个对象:代理者和委托者。
- 代理者:实现协议的某个方法。
委托者:用自己的方法制定要实现协议的方法的对象。
- 协议的两个预编译指令@optional:可以选择的方法。@required:必须执行的方法。
写个小例子:
协议:MyDelegte.h
@protocol MyDelegate <NSObject>
-(NSString *)getString;
@end
// 委托类:
ViewController.h
#import "MyDelegte.h"
@interface ViewController:UIViewController
@property(nonatimic)id<MyDelegate>delegate;
@end
ViewController.m
-(void)viewDidLoad{
SecondViewController *second = [[SecondViewController alloc]init];
self.delegate = second; // 指定代理对象second
NSString *str = [self.delegate getString]; // 获得代理方法的返回值。
}
代理类:
SecondViewController.h
#import "SetStringDelegate.h"
@interface SecondViewController:UITableBarController<SetStringDelegate>
@end
SecondViewController.h
-(NSString *)setString{
return @"helloWorld";
}
// 简单的代理回调也可以把代理对象设置为自身,可以在自身中实现协议方法。
@protocol MyDelegte <NSObject>
-(NSString *)setString;
@end
@protocol MyDelegate
@property(nonatomic,assign)id<MyDelegate>delegate;
-(NSString *)setString;
@end
@end