iOS 中数据的传递

来源:互联网 发布:手机桌面软件排行 编辑:程序博客网 时间:2024/05/29 16:13

 说的数据的传递,在实际开发过程中往往是有两种情况的(目前自认为)


第一种 A 控制器   -------------->  B控制器 (A跳转到B 同时传值到B)

 

第二种(A 跳转到B B传值到A)


第一种传值方法:属性传值

属性创智适合A>B同时传一个值到B,这个也是比较简单的一种方法

控制器B有一个 string;

@property (nonatomic,copy)NSString *testStr;


当控制器A跳转到B时,同时给B的str属性赋值,这样就把一个值从A传到了B 

    BViewController *bView = [[BViewController alloc]init];    bView.testSr = @"属性传值";    [self.navigationController pushViewController:bView animated:YES];

第二种创智方法:代理传值

A控制器传值给B : B是A控制器的代理

首先在A中声明一个协议,也就是借口test2, 里面有一个方法,同时有一个代理(遵守了test2这个协议)delege

@protocol test2 <NSObject>-(void)test2Delege:(NSString *)str;@end@interface ViewController : UIViewController@property (nonatomic,weak)id <test2>delege;


当A要跳转到B的时候,让B去实现协议里的方法:同时把 值传过去;

    BViewController *bView = [[BViewController alloc]init];    self.delege = bView;    [_delege test2Delege:@"A传给B的值是5"];    [self.navigationController pushViewController:bView animated:YES];

B 控制器接受A传过来的值

首相要遵守A中的协议

@interface BViewController : UIViewController <test2>

要实现A中test2协议里的方法;拿到A传过来的值

-(void)test2Delege:(NSString *)str{    _testSr = str;}


前面两种方法适合第一种场景:就是A跳转到B,同时A 传值给B

第三种创智方法:block

首先在B控制器中声明block

typedef void (^BViewBlock)(NSString *test3Str);@interface BViewController : UIViewController@property (nonatomic,copy)BViewBlock test3ViewBlock;@end

要给A传的值

    if (_test3ViewBlock) {        _test3ViewBlock(@"传给A的值");    }


A控制器调转到B控制器时,接收B传回来的值

    BViewController *bView = [[BViewController alloc]init];    bView.test3ViewBlock = ^(NSString *aaa)    {        NSLog(@"B返回====%@",aaa);    };    [self.navigationController pushViewController:bView animated:YES];

第四种创智方法:通知传值


 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(test4:) name:@"testNotification" object:nil];

- (void)test4:(NSNotification *)noto{        NSLog(@"A传过来的值是====%@",noto);}





    NSNotificationCenter *notification = [NSNotificationCenter defaultCenter];    NSMutableDictionary *userinfo = [NSMutableDictionary dictionary];    userinfo[@"test"] = @"通知传值";    [notification postNotificationName:@"testNotification" object:self userInfo:userinfo];

0 0