XNGNotificationProxy 1.0.1

XNGNotificationProxy 1.0.1

xuning0 维护。



  • XuNing 编写

XNGNotificationProxy

英文 | 中文

XNGNotificationProxy 是自定义 NSNotification 的替代品。

NSNotification 使用中的常见场景

您在 VC_U 中关注了某个用户,因此 VC_A 和 VC_B 中的关注按钮应更新状态。

// VC_U.m

[[NSNotificationCenter defaultCenter] postNotificationName:@"UserDidFollowUser"
                                                    object:nil
                                                  userInfo:@{@"isFollowed": @(YES), @"userID": @(123456)}];
// VC_A.m or VC_B.m

[[NSNotificationCenter defaultCenter] addObserverForName:@"UserDidFollowUser"
                                                  object:nil
                                                   queue:nil
                                              usingBlock:^(NSNotification * _Nonnull note) {
                                                  BOOL isFollowed = [note.userInfo[@"isFollowed"] boolValue];
                                                  NSNumber *userID = note.userInfo[@"userID"];
                                              }];

存在许多魔法字符串。我们可能定义一些全局常量字符串来解决这个问题,但我们永远无法直观地知道 userInfo 中的参数。

使用 XNGNotificationProxy

首先您需要一个符合自定义协议的 XNGNotificationProxy 类别。

// XNGNotificationProxy+Protocol.h

@protocol UserActionProtocol <NSObject>
@optional
- (void)userDidFollow:(BOOL)isFollowed userID:(NSNumber *)userID;
@end


@interface XNGNotificationProxy (Protocol) <UserActionProtocol>
@end

然后

// VC_U.m

[[XNGNotificationProxy sharedProxy] userDidFollow:YES userID:@(123456)];
// VC_A.m

@interface VC_A () <UserActionProtocol>
@end

// -viewDidLoad or somewhere else
[[XNGNotificationProxy sharedProxy] registerProtocol:@protocol(UserActionProtocol) forObject:self];

// 
- (void)userDidFollow:(BOOL)isFollowed userID:(NSNumber *)userID {
    // do something
}

要求

iOS 7.0 或更高版本。

安装

有几种方式可以在您的项目中使用XNGNotificationProxy

  • 使用CocoaPods
  • XNGNotificationProxy 文件夹拖入您的项目中

许可证

XNGNotificationProxy遵循MIT许可协议。详细信息请见LICENSE