I have an NSArrayController bound to a Core Data entity — Channel. I have a method that updates the entity after a user changes the title of the Channel:
NSManagedObjectContext *localContext = [NSManagedObjectContext MR_contextForCurrentThread];
NSString * savedTitle = [fieldEditor string];
self.mainWindowController.selectedChannel.channel_name = savedTitle;
[localContext MR_saveToPersistentStoreAndWait];
(I'm using MagicalRecord, in case that's not clear)
By all accounts, this save works — the value is reflected when the change is made, and if I immediately check the persistent store using Core Data Editor I can see the change has been saved.
The problem occurs when I change the view — the change is made in a master view, and the user can switch to a detail view. This line of code, which swaps out the master view, marks the spot where trouble occurs:
[[self.chatsViewController.view animator] removeFromSuperview];
After this line executes, the newly-saved value is gone. Requests to the entity attribute returns an empty string.
But here's the weird part. If I restart the application, the new value is still there! It comes back, and this time it's here to stay. Also, looking at the persistent store, I never see the value disappear at any point. This suggests that my array controller is getting the value taken away somehow.
I've tried refreshing the array controller after the save to "lock it in", as it were. But this appears to have no effect.
Can anyone suggest what steps I might take to track this down? I can't fathom why removing a view would cause this to happen.
Update As I noted in my comment below, I tried putting a log statement on the name attribute's setter in my entity subclass, and it yielded a log entry when I changed the name, but never after.
I've now done another experiment: looking at the Core Data record both before and after the view switch.
NSArray * channels = [Channel MR_findAll];
NSLog(@"Channel: %@", [[channels objectAtIndex:0] channel_name]);
[[self.chatsViewController.view animator] removeFromSuperview];
NSArray * channels2 = [Channel MR_findAll];
NSLog(@"Channel2: %@", [[channels2 objectAtIndex:0] channel_name]);
The result:
Channel: adfasd
Channel2:
I have to be missing something here.
NSArrayController
is "bound to a Core Data entity". Managed objects need a Managed Object Context to live in. Which Managed Object Context are you using to provide your controller with data? Looks like the one shown in your question will just be released, invalidating all Managed Objects which were fetched in it. – Massimo