【问题标题】:Cannot removeObserver?无法移除观察者?
【发布时间】:2014-08-30 04:59:52
【问题描述】:

我已经开始学习 iOS 开发几个星期了,但是这个 bug 让我很困惑......

我只是在 ViewController 中发布了 4 个不同的观察者:(他们有不同的通知名称)

[[NSNotificationCenter defaultCenter]postNotificationName:@"notificationame" object:self userInfo:userinfo];

然后我想在另一个 ViewController 中添加和删除 4 个不同的观察者,如下所示:

  -(void)viewwillappear{      
 self.localChangeObserver=[[NSNotificationCenter defaultCenter]addObserverForName:@"notificationame" object:nil queue:nil usingBlock:^(NSNotification *note) { }];
 }
 -(void)viewwilldisappear{
  [[NSNotificationCenter defaultCenter]removeObserver:self.localChangeObserver];
 }

但是这个“removeObserver”结果不起作用。每次我显示这个 ViewController 时,它都会增加一个观察者,(然后我隐藏这个 VC,什么都没有删除)。所以我最后得到了很多观察者。

而且,将它们放入 ViewDidLoad/dealloc 也不起作用。

但是,另外 2 个观察者工作正常。像这样:

  -(void)viewWillAppear:(BOOL)animated {
   [super viewWillAppear:animated];
   [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
   [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
   }
  - (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self];
 }

我真的不知道我的代码有什么问题。非常感谢。

【问题讨论】:

  • 如果那是您的真实代码,那么问题在于方法名称。 viewwilldisappear 应该是 viewWillDisappear。在每个方法中添加一个NSLog,并确保它在您期望的时候被调用。

标签: ios notifications observer-pattern


【解决方案1】:

试试下面的代码

 [[NSNotificationCenter defaultCenter] removeObserver:self name:@"notificationame" object:nil];

【讨论】:

  • 感谢您的帮助,但它仍然无法正常工作...也许我应该找出其他地方的错误。
【解决方案2】:

使用以下代码:

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    [[NSNotificationCenter defaultCenter] addObserverForName:@"OBSERVER NAME" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *aNotification)
    {
        //Write your Notification handler Code
    }];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"OBSERVER NAME" object:nil];
}

这段代码运行良好...!!!

【讨论】:

  • 感谢您的帮助..但还是不行。可以成功添加观察者,但无法删除观察者。每次我进入这个 ViewController 时,观察者会越来越多,然后是每个帖子通知线索
  • 那么每个发布通知都会使块再次被执行。
  • 请删除您在问题中提到的个人观察者及其名称。 [[NSNotificationCenter defaultCenter] removeObserver:self name:@"UIKeyboardWillShowNotification" object:nil]; [[NSNotificationCenter defaultCenter] removeObserver:self name:@"UIKeyboardWillHideNotification" object:nil];
  • 虽然这段代码不起作用,但您的建议对我帮助很大。最后我发现如果我使用 [addObserverForName:..] 这个总是不能被删除,但是如果我使用 [addObserver:self selector:@selector..] 它可以被删除。我猜这是因为 [postNotificationName:] 只能与后者一起使用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多