2、协议传值
3、Block传值
代替协议代理传值,主要时间点问题。
4、单利传值数据共享。
5、通知传值
通知中心
NSNotificationCenter提供了一种更加解耦的方式。最典型的应用就是任何对象对可以发送通知到中心,同时任何对象可以监听中心的通知。
发送通知的代码如下:
[[NSNotificationCenter defaultCenter]
注册接收通知的代码如下:
[[NSNotificationCenter defaultCenter]
注册通知的时候可以指定一个具体的广播者对象,但这不是必须的。你可能注意到了defaultCenter 。实际上这是你在应用中会使用到的唯一的中心。通知会向整个应用开放,因此只有一个中心。
同时还有一个NSDistributedNotificatio
优点: 通知的发送者和接受者都不需要知道对方。可以指定接收通知的具体方法。通知名可以是任何字符串。
缺点: 较键值观察需要多点代码。在删掉前必须移除监听者。不能传大量数值,只能让谁去做什么事。
1.属性传值
在iOS开发中,我们经常会遇到页面间跳转传值的问题,现归纳总结一下:
情况1:A页面跳转到B页面
方法:
在B页面的控制器中,编写对应的属性,在A页面跳转到B页面的地方,给B的属性赋值即可
代码如下:
//SecondViewController.h
@property
(nonatomic) NSInteger flag;
//当前系统标示(0:其他传值方式;1:block传值方式)
在A页面的试图控制器中
//RootViewController.m
- (IBAction)showSecondView:(id)sender {
SecondViewController *second = [[SecondViewController alloc] initWithNibName:@
'SecondViewController'
bundle:nil];
second.flag = 0;//赋值
跳转传值
[self presentViewController:second animated:YES completion:nil];
}
2.delegate传值 A页面跳转到B页面,B页面再跳转回A页面
设置协议及方法
//SecondViewController.h
//设置代理
@protocol
secondViewDelegate
-(
void
)showName:(NSString *)nameString;
@end
设置代理(为防止循环引用,此处采用了weak)
@interface
SecondViewController : UIViewController
@property
(nonatomic, weak)id<secondViewDelegate> delegate;
@property
(nonatomic, copy) ablock block;
@end
在跳转是调用代理方法
//SecondViewController.m
- (IBAction)delegateMethod:(id)sender {
[self.delegate showName:self.nameTextField.text];
[self dismissViewControllerAnimated:YES completion:nil];