如何通过NSNotificationCenter接收2个通知

时间:2013-08-22 04:12:10

标签: objective-c nsnotificationcenter

我有三种方法:

- (void)viewDidAppear:(BOOL)animated
{
    [self updateViews];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotification:) name:@"itemQuantityChanged" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotification:) name:[NSString stringWithFormat:@"Item %@ deleted", itemUUID] object:nil];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void) receiveNotification: (NSNotification *)notification
{
    if ([[notification name] isEqualToString:@"itemQuantityChanged"])
        [self updateViews];
    if ([[notification name] isEqualToString:[NSString stringWithFormat:@"Item %@ deleted", itemUUID]])
        NSLog(@"FAIL!");
}

主要思想是,对于这个课程,我需要收到2个不同的通知,如果收到它们,则需要执行不同的操作。一切都可以实现吗?我相信可以简化这段代码。如何removeObserver正确?我不使用ARC。

1 个答案:

答案 0 :(得分:2)

您应该为每个通知使用不同的选择器。这样,您不需要方法中的任何逻辑来确定发送了哪个通知。

正如你所做的那样删除观察者很好。