从最简单的页面跳转开始提及, FirstViewController -----> SecondViewControlleratom
方法:直接在跳转处直接给第二个控制器的属性赋值spa
// FirstViewController.m // ... SecondViewController *sec = [SecondViewController new]; sec.backgroundColor = [UIColor RedColor]; // 直接给SecondViewController属性赋值 sec.delegate = self; // 第二种情形使用 [self.navigationController pushViewController:sec animation:YES completion:nil]; // 跳转 // ...
2. 比上面稍微复杂的跳转 , FirstViewController -------> SecondViewController -------->FirstViewController.net
实现功能:FirstViewController 经过某个动做(好比点击按钮) push到SecondViewController中,当SecondViewController 返回的时候,在FirstViewController上的label上显示从SecondViewController中传过来的一个字符串(@“info”)代理
方法1:经过委托delegate的方法实现 (委托方、代理方、协议)code
// SecondViewController.h // step 1 : 建立一个代理(delegate) @protocol secondViewDelegate - (void)showInfo:(NSString *)info; @end @interfacr SecondViewController : UIViewController // step 2 : (委托方)声明一个代理 @property (nonatomic , weak) id<secondViewDelegate>delegate; // weak 是亮点,是为了防止循环引用 @end
// SecondViewController.m - (void)viewWillBackToFirstView{ // step 3 : (委托方)调用delegate方法 [_delegate showInfo:@"info"]; [self.navigationController popViewController]; }
// FirstViewController.m SecondViewController *sec = [SecondViewController new]; // step 4 : (代理方)设置delegate,以便被委托方调用 sec.delegate = self; [self.navigationController pushViewController:sec animation:YES completion:nil]; // step 5 : (代理方)实现协议 - (void)showInfo:(NSString *)info{ self.label.text = info; // 把委托方传过来的字符串显示在界面上 }
代理试用的3个主体:delegate、委托者、代理者blog
代理使用的5个通常步骤字符串
【用@protocol...@end】 建立一个delegateget
【委托者用@property ~~】 声明一个delegate属性animation
【委托者用 [_delegate ~~] 】 调用delegate内的方法io
【代理者用 ~~.delegate = self】 设置delegate,以便委托者调用(步骤3)
【代理者】 实现delegate方法
总结:delegate实现了不一样视图之间的数据交互;delegate属于时间驱动范畴,只有当某一时间触发是,delegate才被调用
方法2:经过block方式实现
// SecondViewController typedef void (^ablock)(NSString *str); // step 1: 在SecondViewController中,声明一个block属性,参数为字符串 <------>对比委托方声明一个代理 @property (nonatomic,copy) ablock block; // @property (nonatomic , weak) id<secondViewDelegate>delegate; // step 2: 在SecondViewController中,调用block <--------> 对比委托方调用delegate方法 self.block(@"info"); // [_delegate showInfo:@"info"]; // [self.navigationController popViewController];
// FirstViewController.h // step 3: 在FirstViewController中,回掉block <----------> 对比代理方实现delegate方法 [self.navigationController pushViewController:sec animation:YES completion:nil]; sec.block = ^(NSString *info){ self.label.text = info }; // sec.delegate = self; // [self.navigationController pushViewController:sec animation:YES completion:nil];
关于block的讲解:有一篇不错的文章http://my.oschina.net/leejan97/blog/268536,讲的很透彻