通知NSNotification常用形式介绍(简单粗暴)

本文详细介绍了NSNotification在Objective-C中的使用方法,包括如何注册监听器、发布通知及移除通知。提供了具体的代码示例,如监听应用进入前后台状态的变化。

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

@注册通知监听器 

//observer:监听器,即谁要接收这个通知
//aSelector:收到通知后,回调监听器的这个方法,并且把通知对象当做参数传入
//aName:通知的名称。如果为nil,那么无论通知的名称是什么,监听器都能收到这个通知
//anObject:通知发布者。如果为anObject和aName都为nil,监听器都收到所有的通知
- (void)addObserver:(id)observer selector:(SEL)aSelector name:(NSString *)aName object:(id)anObject;
 
//name:通知的名称
//obj:通知发布者
//block:收到对应的通知时,会回调这个
//blockqueue:决定了block在哪个操作队列中执行,如果传nil,默认在当前操作队列中同步执行
- (id)addObserverForName:(NSString *)name object:(id)obj queue:(NSOperationQueue *)queue usingBlock:(void (^)(NSNotification *note))block;

@发布通知

发布一个notification通知,可在notification对象中设置通知的名称、通知发布者、额外信息等
- (void)postNotification:(NSNotification *)notification;
 
发布一个名称为aName的通知,anObject为这个通知的发布者
- (void)postNotificationName:(NSString *)aName object:(id)anObject;

发布一个名称为aName的通知,anObject为这个通知的发布者,aUserInfo为额外信息
- (void)postNotificationName:(NSString *)aName object:(id)anObject userInfo:(NSDictionary *)aUserInfo;


@移除通知

- (void)dealloc{

    //  这种形式能移除当前类中的所有通知
    [[NSNotificationCenter defaultCenter] removeObserver:self];

}

@代码样例

//  发布通知
[[NSNotificationCenter defaultCenter] postNotificationName:@"rosterDidEndPopulating" object:self userInfo:@{@"rosterItems":self.rosterItems}];

//  注册监听者
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getValue:) name:@"rosterDidEndPopulating" object:[HMTXMPPManager deafultManager]];

//  方法回调
- (void)getValue:(NSNotification *)notification{
    
    // 取出notification的object
    NSMutableArray *allFriendArray = [NSMutableArray arrayWithArray:notification.userInfo[@"rosterItems"]];

}

//  进入后台时候调用的通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(myMovieFinishedCallback)
                                                 name:UIApplicationDidEnterBackgroundNotification
                                               object:nil];
    
    //  进入前台时候调用的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(videoPlayertongzhi) name:UIApplicationWillEnterForegroundNotification object:nil];


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值