简单实现 NSNotificationCenter 基本功能

NSNotificationCenter 是 iOS 开发当中的通知实现,使用 NSNotificationCenter 可以监听系统事件,也可以发送和接收自定义通知。那么 NSNotificationCenter 是怎么实现的呢? NSNotificationCenter 的源代码,我们至少现阶段无法看到,不过我们可以参考 NSNotificationCenter 的接口来做一个简单的实现。

接口

从 NSNotification.h 文件中,我们可以找到 NSNotificationCenter 的全部接口,这里只是做NSNotificationCenter 简单的原理实现,所以不涉及过多的接口实现,只实现以下的一个单例属性和三个接口

// 单例属性
@property (class, readonly, strong) NSNotificationCenter *defaultCenter;
// 添加通知
- (void)addObserver:(id)observer selector:(SEL)aSelector name:(nullable NSNotificationName)aName object:(nullable id)anObject;
// 发送通知
- (void)postNotificationName:(NSNotificationName)aName object:(nullable id)anObject userInfo:(nullable NSDictionary *)aUserInfo;
// 移除通知
- (void)removeObserver:(id)observer name:(nullable NSNotificationName)aName object:(nullable id)anObject;

对应的自定义 NSNotificationCenter 实现命名为 MyNotificationCenter,分别有以下接口

@interface MyNotificationCenter : NSObject
+ (instancetype)defaultMyCenter;
- (void)addObserver:(id)observer selector:(SEL)aSelector name:(NSString *)aName object:(id)anObject;
- (void)removeObserver:(id)observer name:(NSString *)aName object:(id)anObject;
- (void)postNotificationName:(NSString *)aName object:(id)anObject userInfo:(NSDictionary *)aUserInfo;
@end

和 NSNotificationCenter 息息相关的另一个类是 NSNotification,它的主要属性如下所示

// 通知名称
@property (readonly, copy) NSNotificationName name;
// 发出通知的对象
@property (nullable, readonly, retain) id object;
// 通知携带的额外信息
@property (nullable, readonly, copy) NSDictionary *userInfo;

在这里我们也新建了一个和 NSNotification 相对应的类 MyNotification,用于保存通知的相关信息,接口如下

@interface MyNotification : NSObject
//- (void)postNotificationName:(NSNotificationName)aName object:(nullable id)anObject userInfo:(nullable NSDictionary *)aUserInfo;
// 发送通知时需要保存的信息
@property (nonatomic, strong) NSString *aName;
@property (nonatomic, strong) id anObject;
@property (nonatomic, strong) NSDictionary *aUserInfo;
//- (void)addObserver:(id)observer selector:(SEL)aSelector name:(nullable NSNotificationName)aName object:(nullable id)anObject;
//用于保存监听 aName 通知的所有 observer
@property (nonatomic, strong) NSMutableArray *observers;
@end

有了 MyNotificationCenter 和 MyNotification 类,我们还需要再定义一个 MyObserver 类,用于保存通知观察者的信息,接口如下

@interface MyObserver : NSObject
//- (void)addObserver:(id)observer selector:(SEL)aSelector name:(nullable NSNotificationName)aName object:(nullable id)anObject;
@property (nonatomic,strong) id observer;
@property (nonatomic,assign) SEL aSelector;
@property (nonatomic,strong) NSString *aName;
@property (nonatomic,strong) id anObject;
@end

实现代码

MyNotificationCenter 单例实现

+ (instancetype)defaultMyCenter{
    static MyNotificationCenter *shareInstance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shareInstance = [[self alloc] init];
    });
    return shareInstance;
}

MyNotificationCenter 持有一个 NSMutableArray 类型的属性,该属性用于保存注册的 MyNotification

@implementation MyNotificationCenter{
    NSMutableArray *_myNotifications;
}
- (instancetype)init{
    if (self = [super init]) {
        _myNotifications = [NSMutableArray new];
    }
    return self;
}
@end

MyNotificationCenter 做 addObserver 操作的时候,使用 MyObserver 对象来保存数据,并把 MyObserver 对象放入对应 MyNotification 中,以供 MyNotification 后续发送通知,做 removeObserver 操作时候使用

    // 保存观察者数据
    MyObserver *myObserver = [[MyObserver alloc] init];
    myObserver.observer = observer;
    myObserver.aSelector = aSelector;
    myObserver.aName = aName;
    myObserver.anObject = anObject;
    
    // 添加观察者到对应的通知
    for (int i = 0; i < _myNotifications.count; i++) {
        MyNotification *myNotification = [_myNotifications objectAtIndex:i];
        if ([myNotification.aName isEqualToString:aName]) {
            [myNotification.observers addObject:myObserver];
            return;
        }
    }
    // 若是没有对应的通知,那么新建一个通知
    MyNotification *myNotification = [[MyNotification alloc] init];
    myNotification.aName = aName;
    myNotification.anObject = anObject;
    myNotification.observers = [NSMutableArray new];
    [myNotification.observers addObject:myObserver];
    [_myNotifications addObject:myNotification];

MyNotificationCenter 做 postNotification 操作的时候,需要查找到对应的 MyNotification,并且找到 MyNotification 对应的 Observers, 然后给 Observers 发送消息

- (void)postNotificationName:(NSString *)aName object:(id)anObject userInfo:(NSDictionary *)aUserInfo
{
    // 对通知名称做判空操作
    if (aName && ![aName isEqualToString:@""]) {
       // 查找到对应的通知
        for (int i = 0; i < _myNotifications.count; i++) {
            MyNotification *myNotification = [_myNotifications objectAtIndex:i];
            if ([aName isEqualToString:myNotification.aName]) {
                NSArray *myObservers = myNotification.observers;
                // 取出通知对应的所有观察者
                for (int j = 0; j < myObservers.count; j ++) {
                    MyObserver *myObserver = [myObservers objectAtIndex:i];
                    if ((anObject == nil && myObserver.observer == nil) ||  anObject == myObserver.anObject) {
                        // 给观察者发送消息
                        [myObserver.observer performSelector:myObserver.aSelector withObject:aUserInfo];
                    }
                }
            }
        }
    }
}

MyNotificationCenter 做 removeObserver 操作的时候,需要查找到对应的 MyNotification,比对 NotificationName 找到对应的 Observer,然后移除

- (void)removeObserver:(id)observer name:(NSString *)aName object:(id)anObject
{
    //判空操作
    if (!observer) {
        return;
    }
    // 找到对应的通知
    for (int i = 0; i < _myNotifications.count; i++) {
        MyNotification *myNotification = [_myNotifications objectAtIndex:i];
        if ([myNotification.aName isEqualToString:aName]) {
            // 找到通知的所有观察者
            NSMutableArray *myObservers = myNotification.observers;
            for (int j = 0; j < myObservers.count; j++ ) {
                MyObserver * myObserver = [myObservers objectAtIndex:j];
                if (myObserver.observer == observer) {
                    // 移除对应的观察者
                    [myObservers removeObject:myObserver];
                }
            }
        }
    }
}

总结

这篇文章主要是简单实现 NSNotificationCenter 基本功能,旨在于阐述实现思路,代码上的实现会相对简陋很多。

你可能感兴趣的:(简单实现 NSNotificationCenter 基本功能)