Skip to content

Instantly share code, notes, and snippets.

@zorn
Created October 11, 2011 20:07
Show Gist options
  • Save zorn/1279248 to your computer and use it in GitHub Desktop.
Save zorn/1279248 to your computer and use it in GitHub Desktop.
Core Data KVO / Undo issue
So I have this AddressBookCard entity. It has a BOOL attribute
called shouldSyncWithAddressBook. The idea being when set to YES
we will keep this AddressBookCard in sync with it's AddressBook
brother.
Part of the implementation for the AddressBookCard subclass of
NSManagedObject is some KVO for the shouldSyncWithAddressBook
attribute. When it is changed I check it's value and if YES I
instantly pull in the data from AddressBook.
I set up this KVO in -awakeFromInsert and -awakeFromFetch. I tear
down this KVO in -willTurnIntoFault.
My problem, if you:
* create a AddressBookCard
* save
* delete it
* save
it will trigger the -willTurnIntoFault method and unregister the
KVO
* undo
This will repopulate AddressBookCard but doesn't seem to call
-awakeFromFetch so the KVO is never setup.
* delete
* save
Calls -willTurnIntoFault and attempts to unregister the KVO but
it was never set up. The code I have works around this but
none-the-less I have broken behavior.
What is the best place to setup KVO inside of a NSManagedObject
subclass? Thoughts?
@macoun
Copy link

macoun commented Jan 21, 2013

Hi,
your question is a bit old but I hope it will still help.
The only place you need to re-register an unregistered status from did/willTurnIntoFault is when you delete an object. (Are there any other use cases?)
The following code will register an undo action which is enclosed by the deletion undo group.

- (void)prepareForDeletion {
  [[[[self managedObjectContext] undoManager] prepareWithInvocationTarget: self] awakeFromUndo];
  [super prepareForDeletion];
}

You can of course also call awakeFromFetch instead of awakeFromUndo (which is a user method). I was just not sure what happens if you call [super awakeFromFetch] twice (one from the first fetch and one from the undo action).

Greeting,
Ferhat

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment