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 )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 *)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 )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)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

你可能感兴趣的:(Objective-C 通知(NSNotification))