天天看點

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