Objective-C 通知(NSNotification)

Objective-C的通知是负责对象之间的通信,可以在NSNotificationCenter中注册观察对象,对象也可以NSNotificationCenter发送消息通知.发送对象和接收对象是一对多的关系,通知算是多播(multiCast)形式的一种,如果是向非特定的多个对象发送消息称之为广播(broadcast).

同步 or 异步

通知的注册和发送都是在NSNotificationCenter中实现的,注册观察者,发送消息,还有非常重要的对象销毁的时候注意移除通知.

- (void)addObserver:(id)observer selector:(SEL)aSelector name:(nullable NSNotificationName)aName object:(nullable id)anObject;
#endif

- (void)postNotification:(NSNotification *)notification;
- (void)postNotificationName:(NSNotificationName)aName object:(nullable id)anObject;
- (void)postNotificationName:(NSNotificationName)aName object:(nullable id)anObject userInfo:(nullable NSDictionary *)aUserInfo;

- (void)removeObserver:(id)observer;
- (void)removeObserver:(id)observer name:(nullable NSNotificationName)aName object:(nullable id)anObject;

- (id <NSObject>)addObserverForName:(nullable NSNotificationName)name object:(nullable id)obj queue:(nullable NSOperationQueue *)queue usingBlock:(void (^)(NSNotification *note))block NS_AVAILABLE(10_6, 4_0);
    // The return value is retained by the system, and should be held onto by the caller in
    // order to remove the observer with removeObserver: later, to stop observation.

注册观察者:

 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateData1:) name:@"updateData" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateData2:) name:@"updateData" object:nil];

发送通知:

[[NSNotificationCenter defaultCenter] postNotificationName:@"updateData" object:@{@"age":@"27"} userInfo:@{@"name":@"FlyElephant"}];

收到通知:

- (void)updateData1:(NSNotification *)notificaton {
    sleep(1);
    NSLog(@"收到通知1---%@",notificaton);
}

- (void)updateData2:(NSNotification *)notificaton {
    NSLog(@"收到通知2---%@",notificaton);
}

执行结果:

收到通知1---NSConcreteNotification 0x60800004fc90 {name = updateData; object = {
    age = 27;
}; userInfo = {
    name = FlyElephant;
}}
收到通知2---NSConcreteNotification 0x60800004fc90 {name = updateData; object = {
    age = 27;
}; userInfo = {
    name = FlyElephant;
}}
FENotification[3959:7759128] 通知执行完成

调用通知的方法时,所有相关的观察者都会被有序的发送通知消息,是一个同步的过程,我们可以在收到消息之后异步执行代码,通知如果是在子线程中发出,主线程也会收到通知,最好发送的通知和接收通知都在同一个线程中.Objective-C提供了更简单的机制-通知队列(NSNotificationQueue).

NSNotificationQueue定义如下:

@property (class, readonly, strong) NSNotificationQueue *defaultQueue;
#endif

- (instancetype)initWithNotificationCenter:(NSNotificationCenter *)notificationCenter NS_DESIGNATED_INITIALIZER;

- (void)enqueueNotification:(NSNotification *)notification postingStyle:(NSPostingStyle)postingStyle;
- (void)enqueueNotification:(NSNotification *)notification postingStyle:(NSPostingStyle)postingStyle coalesceMask:(NSNotificationCoalescing)coalesceMask forModes:(nullable NSArray<NSRunLoopMode> *)modes;

- (void)dequeueNotificationsMatching:(NSNotification *)notification coalesceMask:(NSUInteger)coalesceMask;

注册通知:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateData6:) name:@"updateData6" object:nil];

异步发送消息:

    NSNotification *myNotification = [NSNotification notificationWithName:@"updateData6" object:nil];
    [[NSNotificationQueue defaultQueue] enqueueNotification:myNotification postingStyle:NSPostWhenIdle coalesceMask:NSNotificationCoalescingOnName forModes:nil];
    NSLog(@"NSNotificationQueue---通知结束");

执行代码:

- (void)updateData6:(NSNotification *)notificaton {
    sleep(2);
    NSLog(@"NSNotificationQueue收到通知6---%@",notificaton);
}

关于通知队列有两个枚举比较重要:

typedef NS_ENUM(NSUInteger, NSPostingStyle) {
    NSPostWhenIdle = 1,
    NSPostASAP = 2,
    NSPostNow = 3
};

typedef NS_OPTIONS(NSUInteger, NSNotificationCoalescing) {
    NSNotificationNoCoalescing = 0,
    NSNotificationCoalescingOnName = 1,
    NSNotificationCoalescingOnSender = 2
};

NSPostingStyle设置消息发送的时机:
NSPostWhenIdle:在runloop空闲时发送,当runloop要退出时,不会发送.
NSPostASAP:Posting As Soon As Possible,在runloop的当前迭代完成时发送给通知中心,但是当前mode和设定的mode要一致.
NSPostNow:同步调用.

NSNotificationCoalescing是指消息聚合,默认不聚合.
NSNotificationCoalescingOnName:根据通知名称来聚合,如果一段时间多个消息通知,只执行一次.
NSNotificationCoalescingOnSender:根据发送方来聚合.

以下代码聚合类型设置为NSNotificationNoCoalescing执行五次,如果设置为聚合类型,通知只执行一次.

for (NSInteger i = 0; i < 5; i++) {
        NSNotification *myNotification = [NSNotification notificationWithName:@"updateData6" object:nil];
        [[NSNotificationQueue defaultQueue] enqueueNotification:myNotification postingStyle:NSPostWhenIdle coalesceMask:NSNotificationCoalescingOnName forModes:nil];
    }
    NSLog(@"NSNotificationQueue---通知结束");

自定义实现

通知是典型的观察者模式,可以通过NSNotificationCenter提供的方法进行简单的通知实现模拟.

FENotification定义:

@interface FENotification : NSObject

@property (copy, nonatomic) NSString *name;

@property (strong, nonatomic) id object;

@property (copy, nonatomic) NSDictionary *userInfo;

@end

FENotificationCenter定义:

@interface FENotificationCenter : NSObject

@property (class, readonly, strong) FENotificationCenter *defaultCenter;

- (void)addObserver:(id)observer selector:(SEL)aSelector name:(NSString *)aName object:(nullable id)anObject;

- (void)postNotification:(NSString *)notification;
- (void)postNotificationName:(NSString *)aName object:(nullable id)anObject;
- (void)postNotificationName:(NSString *)aName object:(nullable id)anObject userInfo:(nullable NSDictionary *)aUserInfo;

- (void)removeObserver:(id)observer;
- (void)removeObserver:(id)observer name:(nullable NSString *)aName object:(nullable id)anObject;

- (id <NSObject>)addObserverForName:(nullable NSString *)name object:(nullable id)obj queue:(nullable NSOperationQueue *)queue usingBlock:(void (^)(FENotification *note))block NS_AVAILABLE(10_6, 4_0);
// The return value is retained by the system, and should be held onto by the caller in
// order to remove the observer with removeObserver: later, to stop observation.

@end

FENotificationModel定义:

typedef void(^OperationBlock)(FENotification *notification);

@interface  FENotificationModel: NSObject

@property (strong, nonatomic) id observer;

@property (assign, nonatomic) SEL sel;

@property (copy, nonatomic) NSString *notificationName;

@property (strong, nonatomic) id object;

@property (strong, nonatomic) NSOperationQueue *operationQueue;

@property (copy, nonatomic) OperationBlock block;

@end

@implementation FENotificationModel


@end

消息通知内部通过通知名称作为key,多个FENotificationModel对象的数组作为value.

@interface FENotificationCenter()

@property (strong, nonatomic) NSMutableDictionary  *observerDict;

@end

单例实现:

#pragma mark - LifeCycle

+ (FENotificationCenter *)defaultCenter {
    static FENotificationCenter *sharedCenter = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedCenter = [[FENotificationCenter alloc] init];
    });
    return sharedCenter;
}

#pragma mark - Accessors

- (NSMutableDictionary *)observerDict {
    if (!_observerDict) {
        _observerDict = [[NSMutableDictionary alloc] init];
    }
    return _observerDict;
}

添加观察者:

- (void)addObserver:(id)observer selector:(SEL)aSelector name:(NSString *)aName object:(id)anObject {
    
    FENotificationModel *model = [[FENotificationModel alloc] init];
    model.observer = observer;
    model.sel = aSelector;
    model.notificationName = aName;
    model.object = anObject;
    
    NSMutableArray *value = [self.observerDict objectForKey:aName];
    if ([value count]) {
        [value addObject:model];
    } else {
        NSMutableArray *arr = [[NSMutableArray alloc] init];
        [arr addObject:model];
        self.observerDict[aName] = arr;
    }
}

- (id<NSObject>)addObserverForName:(NSString *)name object:(id)obj queue:(NSOperationQueue *)queue usingBlock:(void (^)(FENotification *))block {
    
    FENotificationModel *model = [[FENotificationModel alloc] init];

    model.notificationName = name;
    model.operationQueue = queue;
    model.block = block;
    
    NSMutableArray *value = [self.observerDict objectForKey:name];
    if ([value count]) {
        [value addObject:model];
    } else {
        NSMutableArray *arr = [[NSMutableArray alloc] init];
        [arr addObject:model];
        self.observerDict[name] = arr;
    }
    return nil;
}

发送通知实现:

- (void)postNotification:(NSString *)notification {
    [self postNotificationName:notification object:nil];
}

- (void)postNotificationName:(NSString *)aName object:(id)anObject {
    [self postNotificationName:aName object:anObject userInfo:nil];
}

- (void)postNotificationName:(NSString *)aName object:(id)anObject userInfo:(NSDictionary *)aUserInfo {
    NSMutableArray *value = self.observerDict[aName];
    if ([value count]) {
        
        for (FENotificationModel *model in value) {
            
            if (model.operationQueue) {
                NSOperationQueue *queue = model.operationQueue;
                NSBlockOperation *blockOperation = [NSBlockOperation blockOperationWithBlock:^{
                    FENotification *notification = [FENotification new];
                    notification.name = model.notificationName;
                    model.block(notification);
                }];
                [queue addOperation:blockOperation];
                
            } else {
                id observer = model.observer;
                SEL sel = model.sel;
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
                
                FENotification *notification = [FENotification new];
                notification.name = aName;
                notification.object = anObject;
                notification.userInfo = aUserInfo;
                [observer performSelector:sel withObject:notification];
            }
        }
    }
}

移除观察者:

- (void)removeObserver:(id)observer {
    
    for (NSString *key in [self.observerDict allKeys]) {
        
        NSMutableArray *data = self.observerDict[key];
        NSMutableArray *newData = [NSMutableArray new];
        for (NSInteger i=0; i < [data count]; i++) {
            FENotificationModel *model = data[i];
            if (model.observer != observer) {
                [newData addObject:model];
            }
        }
        
        if ([newData count] == 0) {
            [self.observerDict removeObjectForKey:key];
        } else {
            self.observerDict[key] = newData;
        }
    }
}

- (void)removeObserver:(id)observer name:(NSString *)aName object:(id)anObject {
    for (NSString *key in [self.observerDict allKeys]) {
        if (key == aName) {
            NSMutableArray *data = self.observerDict[key];
            NSMutableArray *newData = [NSMutableArray new];
            for (NSInteger i=0; i < [data count]; i++) {
                FENotificationModel *model = data[i];
                if (model.observer != observer) {
                    [newData addObject:model];
                }
            }
           
            if ([newData count] == 0) {
                [self.observerDict removeObjectForKey:key];
            } else {
                self.observerDict[key] = newData;
            }
        }
    }
}

参考链接:
NSNotifications

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,539评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,594评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,871评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,963评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,984评论 6 393
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,763评论 1 307
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,468评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,357评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,850评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,002评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,144评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,823评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,483评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,026评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,150评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,415评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,092评论 2 355

推荐阅读更多精彩内容