iOS传值二block传值,通知传值

上一章我们讲了页面传值的两种方法属性传值和代理传值,这一章继续讲解其他传值方法

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];

}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章