0
收到2個通知我有三個方法:如何通過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。
似乎很好,但我通常在viewDidLoad中訂閱並在dealloc中取消訂閱。 – Jeremy