iOS 简单使用通知模式

今天在写了一个天气预报模块,切换城市时,要传值给显示天气的controller里,选择城市有一级和二级界面,二级界面使用代理不好实现,用到了通知模式,也就是

NSNotificationCenter类。

首先我在二级controllercell上触发点击事件代码如下:

- (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 standardUserDefaultssynchronize]会出现数据丢失。

最后是把这个通知移除,这里有个注意的点,就是要把移除的方法放到

- (void)viewWillDisappear:(BOOL)animated

放进deollc里是没用的。这个通知是系统唯一的,销毁不了,只能移除。

新手求上进,不对的地方大神门请指点。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值