0

I am using NSNotificationCenter in a code .

[[NSNotificationCenter defaultCenter]addObserverForName:@"NextIndexNotification" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {

    [self receiveTestNotification:note];
    [[NSNotificationCenter defaultCenter] removeObserver:note];


}];

- (void)receiveTestNotification:(NSNotification *) notification
{
    NSDictionary *userInfo = notification.userInfo;
    NSString *strServerResultID = [userInfo objectForKey:@"valServerResultID"];
}

//// And I am adding Notification center here ...

            dispatch_async(dispatch_get_main_queue(),^{
                NSDictionary *userInfo = [NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"%@",[[PerformXMLXPathQuery(responseData,xPathQuery) objectAtIndex:0] valueForKey:kNodeContent]] forKey:@"valServerResultID"];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"NextIndexNotification" object:self userInfo:userInfo];

            });

in this code , remove notification doesn't being called and my code move to infinite loop .

where am I doing wrong ?

Jean-Luc Godard
  • 1,873
  • 3
  • 28
  • 53
  • 2
    I'm not sure if it solves your problem but I see that you're removing the notification, not the observer – Andrey Chernukha Aug 22 '14 at 12:11
  • A couple of things: 1. What is the function receiveTestNotification doing with its reference to note? If at any point you have create a strong reference to it, you may not be able to remove it. 2. Where are you creating the notification itself? In other words, there is not enough info to answer your question as written. – joelg Aug 22 '14 at 12:12
  • this http://stackoverflow.com/questions/8477629/why-doesnt-remove-observer-from-nsnotificationcenteraddobserverfornameusingbl?rq=1 may help – gro Aug 22 '14 at 12:34

3 Answers3

0

Instead of passing note (which is the Notification itself, not the observer), pass the return value from the addObserverForName call to removeObserver, like this:

__block id observer = [[NSNotificationCenter defaultCenter] addObserverForName:@"NextIndexNotification" 
                      object:nil 
                       queue:[NSOperationQueue mainQueue] 
                  usingBlock:^(NSNotification *note)
{
    [self receiveTestNotification:note];
    [[NSNotificationCenter defaultCenter] removeObserver:observer];
}];
Gereon
  • 17,258
  • 4
  • 42
  • 73
0

Try
[[NSNotificationCenter defaultCenter] removeObserver:nil];

Parag Shinde
  • 176
  • 11
0

Remove notification by using blocks.

[[NSNotificationCenter defaultCenter] removeObserver:self];
josh
  • 1,681
  • 4
  • 28
  • 61