天天看点

IOS代理协议与委托

今天看到一个哥们总结delegate和protocol关系用了这样的一个比喻,觉得很贴切,拿来给大家分享一下:

      把自己不想干的一些事情(洗衣做饭)找个助手来帮助你做,而你要的这个助手得有一定的能力,不是任何一个人都可以的,所以你就得有个招聘要求。好了,协议(protocol)就类似于你的招聘要求,你找到的助手就是代理(delegate)。  这样就有了  我.delegate = 助手;好了,这样以后再有洗衣做饭的活直接找助手做就可以了。

    协议不是类,以@protocol关键字声明, 协议有两个对象:代理者和委托者。

    代理者:实现协议的某个方法。

    委托者:用自己的方法制定要实现协议的方法的对象。

    协议的两个预编译指令@optional(/ˈɔpʃənl/):可以选择的方法。@required:必须执行的方法。

写个小例子:

协议:HelloworldDelegte.h

    @protocol HelloworldDelegate <NSObject>

    -(NSString *)getString;

    @end

委托类:

 ViewController.h

  #import "HelloworldDelegte.h"

  @interface ViewController:UIViewController

    @property(nonatimic)id<HelloWorldDelegate>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 HelloWorldDelegte <NSObject>

   -(NSString *)setString;

@end

@protocol HelloWorldDelegate

@property(nonatomic,assign)id<HelloWorldDelegate>delegate;

-(NSString *)setString;

@end

@end