今天在写了一个天气预报模块,切换城市时,要传值给显示天气的controller里,选择城市有一级和二级界面,二级界面使用代理不好实现,用到了通知模式,也就是
NSNotificationCenter类。
首先我在二级controller的cell上触发点击事件代码如下:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"点击二级页面 %d",indexPath.row);
[self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:1] animated:YES];
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc postNotificationName:@"District" object:self userInfo:[self.dataArray objectAtIndex:indexPath.row]];
}
我这个时传的一个城市代码;
在天气controlloer里利用这个城市代码参数,重新请求url;下面是接受通知的代码:
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
self.navigationController.navigationBar.tintColor = [UIColor blackColor];
self.navigationItem.title=@"天气预报";
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(recvBcast:) name:@"District" object:nil];
}
- (void)recvBcast:(NSNotification*)noti
{
//获取所传的参数
NSDictionary *dict1 = (NSDictionary*)[noti userInfo];
code = [dict1 objectForKey:@"code"];
[[NSUserDefaults standardUserDefaults] setObject:code forKey:@"cityCode"];
//这个是长期保存数据的
[[NSUserDefaults standardUserDefaults] synchronize];
NSLog(@"code 是 %@",code);
[self loadweather_now];
[self loadWeatherData];
}
不写[[NSUserDefaults standardUserDefaults] synchronize]会出现数据丢失。
最后是把这个通知移除,这里有个注意的点,就是要把移除的方法放到
- (void)viewWillDisappear:(BOOL)animated
放进deollc里是没用的。这个通知是系统唯一的,销毁不了,只能移除。
新手求上进,不对的地方大神门请指点。