我有一个观察者,可以将其称为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这样的类,然后将通知发布到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的操作方法
-(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/

10-14 22:18
查看更多