Notification的简单使用

Notification也是通过扩展的方式接进去的,目前支持的功能有:

  • JS->JS
  • JS->Native
  • Native->JS

扩展的方法如下:

- (void)postNotificationName:(NSString *)notificationName object:(id)notificationSender userInfo:(NSDictionary *)userInfo;
- (void)addNotificationName:(NSString *)notificationName processor:(NSDictionary *)processor object:(id)notificationSender;
- (void)removeNotificationName:(NSString *)notificationName instanceName:(NSString *)instanceName;

分别为:
发起Notification
添加Notification
移除Notification

详细实现代码如下:

- (void)postNotificationName:(NSString *)notificationName object:(id)notificationSender userInfo:(NSDictionary *)userInfo {

    [[NSNotificationCenter defaultCenter] postNotificationName:notificationName object:notificationSender userInfo:userInfo];
}

- (void)addNotificationName:(NSString *)notificationName processor:(NSDictionary *)processor object:(id)notificationSender {

    if (notificationName && [processor isKindOfClass:[NSDictionary class]]) {

        if (!_processors[notificationName]) _processors[notificationName] = [[NSMutableArray alloc] initWithCapacity:0];

        (!processor) ?: [_processors[notificationName] addObject:processor];

    }

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(p_handleNotification:) name:notificationName object:notificationSender];
}

- (void)removeNotificationName:(NSString *)notificationName instanceName:(NSString *)instanceName {

    if (!notificationName || !instanceName) {

        return;
    }

    [_processors[notificationName] enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([instanceName isEqualToString:obj[kInstanceName]]) {

            [_processors removeObjectForKey:obj];
        }
    }];
}

- (void)p_handleNotification:(NSNotification *)notify {

    [_processors[notify.name] enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {

        [[NJCSBridge getInstance] runJSFunctionWithConfigures:obj];

    }];
}

使用示例:

var notifiConfig = {kInstanceName:"VCInstanceName", kMethodName:"methodName"};//生成配置
nativeBridge.addNotificationName_processor("NOTIFICATIONNAME", notifiConfig, null);//添加监听
nativeBridge.postNotificationName("NOTIFICATIONNAME", null, null);//发起通知

热评文章