說的數據的傳遞,在實際開發過程中往往是有兩種情況的(目前自認爲)
第一種 A 控制器 --------------> B控制器 (A跳轉到B 同時傳值到B)
第二種(A 跳轉到B B傳值到A)
第一種傳值方法:屬性傳值
屬性創智適合A>B同時傳一個值到B,這個也是比較簡單的一種方法
控制器B有一個 string;
@property (nonatomic,copy)NSString *testStr;
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];