首页投稿(暂停使用,暂停投稿)iOS学习开发iOS Developer

NSNotificationCenter实现原理

2016-06-28  本文已影响635人  NexTOne

NSNotificationCenter是使用观察者模式来实现的用于跨层传递消息。

观察者模式

定义对象间的一种一对多的依赖关系。当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并自动更新。

简单的源码样例

注意点:

@interface NTOObserver : NSObject

@property (nonatomic, strong) id observer;
@property (nonatomic, assign) SEL selector;
@property (nonatomic, copy) NSString *notificationName;

@end

NTONotificationCenter对象的实现

@interface NTONotificationCenter : NSObject

+ (NTONotificationCenter *)defaultCenter;

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

- (void)postNotificationName:(NSString *)aName;
 
@end
@interface NTONotificationCenter ()

@property (nonatomic, strong) NSMutableArray *observers;

@end

@implementation NTONotificationCenter

- (instancetype)init {
    if (self = [super init]) {
        _observers = [NSMutableArray array];
    }
    return self;
}

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

- (void)addObserver:(id)observer selector:(SEL)aSelector name:(NSString *)aName {
    NTOObserver *model = [[NTOObserver alloc] init];
    model.observer = observer;
    model.selector = aSelector;
    model.notificationName = aName;
    [self.observers addObject:model];
    
}

- (void)postNotificationName:(NSString *)aName {
    [self.observers enumerateObjectsUsingBlock:^(NTOObserver *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([aName isEqualToString:obj.notificationName]) {
            [obj.observer performSelector:obj.selector];
        }
    }];
}
上一篇 下一篇

猜你喜欢

热点阅读