上一章我們講了頁面傳值的兩種方法屬性傳值和代理傳值,這一章繼續講解其他傳值方法
1.block傳值
如要將B頁面的值傳到A頁面,在B頁面做一下設置
typedef void (^peopleMessage)(NSString *str);
@property (nonatomic, copy) peopleMessage block;
在B頁面返回A頁面的方法裏
-(void)showMyBlock{
self.block(@”我是Block傳值”);
[self dismissViewControllerAnimated:YES completion:nil];
}
在A試圖顯示,回調block
- (void)showSecondWithBlock:(UIbutton)btn{
SecondViewController *second =[[SecondViewController alloc]initWithNibName:@'SecondViewController'bundle:nil];
[self presentViewController:second animated:YES completion:nil];
second.block = ^(NSString *str){
NSLong(@”%@”,str)
};
}
2.通知傳值
通知傳值分兩種情況,一是傳遞字典,二是傳遞數組
一:傳遞字典
在A頁面的控制器中,註冊通知:
- (void)viewDidLoad{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(nameChange:) name:@"tongzhi" object:nil];
}
-(void)nameChange::(NSNotification*)notification{
NSDictionary *dic = [notification userInfo];
NSLong(@"%@", dic[@"name"]);
}
在B頁面返回A頁面的方法裏發送通知
- (void)postNotification {
[[NSNotificationCenter defaultCenter] postNotificationName:@"tongzhi" object:self userInfo:@{@"name":我 是通知傳值}];
[self dismissViewControllerAnimated:YES completion:nil];
}
通知不使用時要銷燬
-(void)dealloc{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
二:傳遞數組
- (void)viewDidLoad{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(nameChange:)name:@"area" object:nil];
}
-(void)nameChange::(NSNotification*)notification{
NSArray *arr = [notification object];
NSLong(@"%@", arr);
NSLog(@"%@",[arr objectAtIndex:0]);
NSLog(@"%@",[arr objectAtIndex:1]);
NSLog(@"%@",[arr objectAtIndex:2]);
}
在B頁面返回A頁面的方法裏發送通知
- (void)postNotification {
NSArray *arr = [NSArray arrayWithObjects:@"北京",@"上海",@"深圳",nil];
[[NSNotificationCenter defaultCenter]postNotificationName:@"area"object:arr];
[self dismissViewControllerAnimated:YES completion:nil];
}
通知不使用時要銷燬
-(void)dealloc{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}