NSNotificationCenter 上的 Observer 可以处理多个通知

Observer on NSNotificationCenter that can handle multiple notifications

我有一个观察者,我们称它为 Subscriber,我想像这样在 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 然后 post 通知到 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"

// 到 post 通知调用此方法并给出 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
    }
}