NSNotificationCenter实现原理

作者: NexTOne | 来源:发表于2016-06-28 11:51 被阅读635次

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

    观察者模式

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

    简单的源码样例

    注意点:

    • 观察者接收到通知后执行任务的代码在发送通知的线程中执行
    • 需要先注册监听再发送通知才能正确监听
      定义一个观察者model用于保存观察者的各种信息
    @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];
            }
        }];
    }
    

    相关文章

      网友评论

        本文标题:NSNotificationCenter实现原理

        本文链接:https://www.haomeiwen.com/subject/usktjttx.html