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

时间:2015-08-27 03:26:43

标签: ios nsnotificationcenter nsnotifications

我有观察员让我们称之为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。我该如何做到这一点?

1 个答案:

答案 0 :(得分:3)

//创建常量字符串

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

//发布一个notfication调用此方法并给出原因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
    }
}