selcuk
selcuk

Reputation: 73

Adding 2 observer with one name in NSNotificationCenter in 1 class

I have a observer problem with NSNotificationCenter in my app.

My AppDelegate class has 2 service class to get data by url which called ExhibitionService & NewsService.

This 2 service class uses one Queueloader class in itself.

When I wrote 2 observer to listen service load operations in my appdelegate class, it returns error and crashes.

APP DELEGATE CLASS

ExhibitionLoaderService *exhibitionService = [[ExhibitionLoaderService alloc] init]; 

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(exhitibionServiceComplete :) name:**CserviceComplete** object:nil];

[exhibitionService load];

NewsLoaderService *newsService    = [[NewsLoaderService alloc] init]; 

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(newsServiceComplete :) name:**CserviceComplete** object:nil];

[newsService load];

ExhibitionLoaderService.m & NewsLoaderService has the same method

-(void)load
{
    Queueloader *que = [[Queueloader alloc] initWithPath:CExhibitionURLPath isVerbose:NO];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didQueComplete:) name:CdidQueueloaderComplete object:nil];
    [que startOperation];
    [que release];
}

ERROR I GOT

[[NSNotificationCenter defaultCenter] postNotificationName:**CdidQueueloaderComplete** object:results];

2 service class has CdidQueueloaderComplete... Problem is about observers but how? what?
PS. Program received signal EXC_BAD_ACCESS.

Thanks.

Upvotes: 0

Views: 2122

Answers (1)

user23743
user23743

Reputation:

There's no problem with having multiple observers of the same notification. The problem you describe sounds a lot like it's related to the lifetime of your observers.

If you deallocate an object that's still registered to listen to notifications, the NSNotificationCenter doesn't know about that. If a notification comes in in the future, the center will forward it to the object it thinks is still listening (but that has gone away), and you get a crash.

The solution to this problem is to ensure that your object is removed as an observer before it is destroyed. There are two ways to do this:

  • often you'll know when an object should start or stop listening to notifications, and you can make sure you remove it as an observer when it should stop (for example, perhaps view controllers should start listening for model updates when their views appear and stop listening when their views disappear)
  • other times, an object can look after its own notification lifecycle: perhaps you can start listening in an initialiser and stop listening in -dealloc.

Whatever way you do it, you need to balance adding observers and removing observers so that when an object goes away it's no longer registered with the notification center.

Upvotes: 1

Related Questions