ios - NSNotificationCenter 上的观察者可以处理多个通知

标签 ios nsnotificationcenter nsnotifications

我有一个观察者,我们可以将其称为订阅者,我希望将其注册到NSNotificationCenter上,如下所示:

NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter addObserver:self
                    selector:@selector(post:)
                    name:nil
                    object:nil];

其中post:是:

- (void)post:(NSNotification *)notification {
    if (notification == nil) {
        // Throw an exception
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:nil object:nil];
}

我想扩展Subscriber并创建PictureSubscriber之类的类,然后将通知发布到PictureSubscriber并让它处理多种类型的通知像这样:

PictureViewController

[[NSNotificationCenter defaultInstance] postNotification:@"UpdatePictureNotification" object:self userInfo:urlDict];

...

[[NSNotificationCenter defaultInstance] postNotification:@"DeletePictureNotification" object:self userInfo:urlDict];

那么理想情况下,我希望PictureSubscriber能够接收不同类型的NSNotification。我该如何实现这个目标?

最佳答案

//创建常量字符串

#define kUpdatePictureNotification @"UpdatePictureNotification"
#define kDeletePictureNotification @"DeletePictureNotification"
#define kReasonForNotification @"ReasonForNotification"
#define kPictureNotification @"PictureNotification"

//要发布通知,请调用此方法并给出 kUpdatePictureNotification 或 kDeletePictureNotification 的原因

-(void)postNotificationGivenReason:(NSString *)reason
{
    NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:
                          reason, kReasonForNotification,
                            // if you need more stuff add more
                          nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:kPictureNotification object:nil userInfo:dict];

}

//这是观察者:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pictureNotification:) name:kPictureNotification object:nil];

//这里是pictureNotification的action方法

-(void)pictureNotification:(NSNotification *)aNotification
{
    NSString *reason = [aNotification.userInfo objectForKey:kReasonForNotification];
    if ([reason isEqualToString:kUpdatePictureNotification])
    {
        // It was a UpdatePictureNotification
    }
    else
    {
        // It was a DeletePictureNotification
    }
}

关于ios - NSNotificationCenter 上的观察者可以处理多个通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32240181/

相关文章:

ios - UISwipeGestureRecognizer 动画

ios - NSNotificationCenter 永远不会被执行

xcode - NSDistributedNotifications 未在(相同)应用程序的实例之间分发

cocoa - 使用通知从 NSTask 实时获取数据不起作用

ios - 收到 NSNotification 的速度有多快?

ios - 设备旋转时如何为 View 设置正确的边界?

ios - 如何在 iOS 设备上自定义滚动条

ios - 键盘显示/隐藏的通知中心在 iOS 11 中不起作用

ios - 在 viewWillAppear/viewWillDisappear 中添加观察者/移除观察者

iOS:特定时间的区域监控