【发布时间】:2014-04-24 12:16:57
【问题描述】:
我在视图控制器中有一个方法可以设置一些通知:
- (void)processState
{
MYGame *game = [[MYGameManager sharedInstance] getGameAtIndex:self.indexPath.row];
if(game)
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notification_gameUpdated:) name:kMYNotificationGameUpdated object:game];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notification_gameEnded:) name:kMYNotificationGameEnded object:game];
}
}
还有一个游戏更新方法,经常调用:
- (void)notification_gameUpdated:(NSNotification *)notification
{
MYGame *game = notification.object;
_game_status = (game.entity.bet.isWinning) ? MYGameStatusWin : MYGameStatusLose;
}
最后,当游戏结束时:
- (void)notification_gameEnded:(NSNotification *)notification
{
MYGame *game = notification.object;
// Clear the notifications
[[NSNotificationCenter defaultCenter] removeObserver:self name:kMYNotificationGameUpdated object:game];
[[NSNotificationCenter defaultCenter] removeObserver:self name:kMYNotificationGameEnded object:game];
self.gameIsActive = NO;
}
麻烦的是,即使我移除了观察者(断点显示这种情况正在发生),notification_gameUpdated: 方法仍然仍然被调用。如果我把它改成
[[NSNotificationCenter defaultCenter] removeObserver:self name:kMYNotificationGameUpdated object:nil];
这仍然无法清除它。但是如果我把它改成
[[NSNotificationCenter defaultCenter] removeObserver:self name:nil object:game];
那么确实清除它。一样
[[NSNotificationCenter defaultCenter] removeObserver:self];
但我也不热衷于这样做,因为我宁愿代码是干净的,并且如果我需要添加更多观察者,我不希望任何“陷阱”。我检查了其余的代码,找不到任何其他类向这个对象添加观察者,尽管其他视图控制器确实监听了相同的消息。
【问题讨论】:
-
在
processState中添加一条日志消息,看看它是否被多次调用。 -
我做到了,它只被调用过一次。
-
游戏是否会覆盖 isEqual?
-
嗯,你很可能会在那里找到一些东西。游戏对象扩展了一个名为 BaseModel 的类 - github.com/nicklockwood/BaseModel - 我不太了解它的作用,但它确实包含
encodeWithCoder:之类的东西,所以我会咨询我的同事并报告! :) -
我发现了问题所在... 方法混乱!我会在这里将其标记为答案。抱歉浪费了大家的时间!
标签: objective-c nsnotificationcenter nsnotifications