通知 NSNotification

本文介绍了如何在iOS开发中利用NSNotification实现不同组件间的解耦通信。包括NSNotification的基本用法,如注册、发送和移除通知,以及如何通过传递自定义参数来增强通知的功能。特别强调了在处理耗时任务时应考虑线程安全的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#define QuitToDeleteCache @"QuitToDeleteCache"


//注册通知 
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(updatePredictor:) name:QuitToDeleteCache object:nil];


//移除通知
 [[NSNotificationCenter defaultCenter] removeObserver:self name:QuitToDeleteCache object:nil];


//发送通知

[[NSNotificationCenter defaultCenter] postNotificationName:QuitToDeleteCache object:nil userInfo:nil];



如果传递的参数有多个可以通过

[[NSNotificationCenter defaultCenter] postNotificationName : NOTIF_DataComplete object:nil userInfo: nil];userInfo后面跟的是一个NSDictionary,我们可以将要传递的多个参数都装到NSDictionary然后进行传递。取出来的时候只要通过notification.userInfo来取得这个字典

重要提示:应用这种模式需要注意的是消息中心对消息的分发是同步的,也就是说消息在发送到下一个接收者之前需要前一个接受者快速返回,否则就会阻塞下一个接收者消息,所以对于长时间的消息处理,需要另外启动一个线程来单独处理消息接收后的任务,确保在接收到消息以后立即返回。


//传参

{

    NSMutableDictionary* faDictonary = [NSMutableDictionarydictionary];  ;

    [faDictonary setValue:[NSNumber numberWithInt: 112] forKey:@"Number_112"];

    [faDictonary setValue:selectArray forKey:@"Array_selecte"];

    [[NSNotificationCenterdefaultCenter]postNotificationName:QuitToDeleteCacheobject:niluserInfo:faDictonary];

}

//取出

-(void)updatePredictor:(NSNotification*)notification

{

    NSNumber *nWhich = [notification.userInfoobjectForKey:@"Number_112"];

    NSMutableArray* array = [notification.userInfoobjectForKey:@"Array_selecte"];

    NSLog(@"%d",[nWhich intValue]);

    for (int i = 0; i<[array count]; i++) {

        NSLog(@"%@",[array objectAtIndex:i]);

    }


}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值