ios開發(fā)中控制器與控制器之間的傳值與聯(lián)系,使用最多的是block,代理,通知.那么他們之間有什么區(qū)別以及怎么使用的呢,下面一一道來.
-
block的使用,特點:簡單易用,簡潔.
一般使用存代碼時,避免不了涉及到對象/控制器之間的傳值,那么一般最常用的就是block,block的使用必須是2個控制器/對象之間具有關(guān)聯(lián)性,例如在一個uiviewcontroller鐘加入tableview,如若要把cell中的值或者點擊事件傳到控制器,那么必須先傳到tableview,再傳到控制器.代碼如下
- cell在該方法中將model的數(shù)據(jù)傳給tableview中的didClickButton:model.方法
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
self.myCell.didButton = ^(AroundMainModel* model){
[weakSelf didClickButton:model];
};
}
- 在tableview的didClickButton中通過block將Model傳給控制器
-(void)didClickButton:(AroundMainModel*)model{
if (self.didButton) {
self.didButton(model);
}
}
//在控制器中接收到Model.
_historyAddressTableView.didButton = ^(AroundMainModel* model){
[weakSelf didClickButton1:model];
};
- 然后在控制器中的該方法就會調(diào)用,達(dá)到點擊cell中的方法,觸發(fā)控制器中的方法,并將cell中的數(shù)據(jù)傳給控制器.
-(void)didClickButton1:(AroundMainModel*)model{
AddCommonPathViewController *addVC = [[AddCommonPathViewController alloc]init];
addVC.model = model;
[self.navigationController pushViewController:addVC animated:YES];
}
-
通知的使用.特點:一對多傳值,控制器與控制器之間可以沒有關(guān)聯(lián).
一般在一個點有改動,需要其他點做出反應(yīng)時使用.簡單的代碼如下:
- 發(fā)出通知
[[NSNotificationCenter defaultCenter] postNotificationName:@"EnterForeground" object:nil];
- 接收通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appGoBackgroud) name:@"EnterForeground" object:nil];
- 在接收通知的方法中寫接到通知后的操作.
-(void)appGoBackgroud{
self.goBackgroundDate = [NSDate date];
}
- 移除通知,控制器銷毀時需要移除通知.如果不移除,因為該控制器已經(jīng)銷毀,當(dāng)發(fā)出通知時,程序就會崩潰.
-(void)dealloc
{
[[NSNotificationCenter defaultCenter]removeObserver:self];
}
- 注:如果通知中需要傳值的話,在發(fā)出的通知中,加入userinfo,格式為字典.
[[NSNotificationCenter defaultCenter]postNotificationName:@"timeGone" object:nil userInfo:@{@"timeGone":[NSString stringWithFormat:@"%F",timeGone]}];
- 然后在接收通知時,就可以在通知的方法中獲取到NSnotification對象該對象有userinfo屬性,他就是我們在通知中傳輸?shù)男畔?
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(timeGone:) name:@"timeGone" object:nil];
-(void)timeGone:(NSNotification*)noti{
NSLog(@"%@",noti);
NSString* timeGone = [noti.userInfo valueForKey:@"timeGone"];
-
代理的使用.代理的使用與block類似,他也是一對一傳值,使用上更加直觀.代碼省略,沒事多百度.