views:

232

answers:

2

I'm trying a multithreaded Core Data implementation on iPhone SDK 3.1.3. I have two different NSManagedObjectContext objects for each thread and I am registering for the change notifications on one thread like below:

- (void)setup {
    DLog(@"Registering for NSManagedObjectContext notifications");
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    [nc addObserver:self selector:@selector(test:) name:@"NSManagedObjectContextWillSaveNotification" object:nil];
    [nc addObserver:self selector:@selector(test:) name:@"NSManagedObjectContextDidSaveNotification" object:nil];
    [nc addObserver:self selector:@selector(test:) name:@"NSManagedObjectContextObjectsDidChangeNotification" object:nil];
}

- (void)test:(NSNotification *)notif {
    DLog(@"Test callback");
}

In my other thread I am saving the second context like so:

NSError *error = nil;
[managedObjectContext save:&error];

if (error) {
    ALog(@"Error occured while trying to save a NewsStory object");
}
else {
    DLog(@"Saving context");
}

The notification callback method never gets executed though, which makes me believe these notifications are never posted?

My log shows the following:

Registering for NSManagedObjectContext notifications
Saving context
...
Saving context
A: 

One thing I know causes problems with notifications and Core Data is having a custom managed object subclass that is not properly key-value observing compliant. This prevents the change notifications from being created in the first place.

As a test, I would suggest registering an observer in the same thread or even having the subclass (if you use them) register to observe themselves. If that doesn't work then you problem is more basic than the notifications. If it does work, then your problem is in your threading.

TechZen
+5  A: 

Switch your @"NSManagedObjectContextWillSaveNotification" to NSManagedObjectContextWillSaveNotification. Those are constants. The events are most likely being posted but you are not listening for the right name.

Marcus S. Zarra
Doh! How silly of me :( Thanks Marcus
nduplessis
Good catch! I skimmed right past that.
TechZen