Reputation: 690
In my app, users are able to quickly switch back and forth between objects and edit the text on those objects.
While they press "undo," I want to bring up the relevant object so they can see the undo they are performing.
The objects are instances of an NSManagedObject
subclass, and I'm using the undo manager that comes with the managedObjectContext
you get when you create a UIManagedDocument
.
The undo & redo is functioning fine otherwise.
How can I tell which object is being 'undone' for a given undo operation?
Upvotes: 0
Views: 133
Reputation: 690
So I figured this out. The method I needed was:
Which can be overridden in a subclass of NSManagedObject.
This method gets called whenever an object is affected by an undo or a redo. I was previously under the impression it only got called when an undo inserts or deletes an object, but it gets called if an object is changed as well.
What I do in this method is post a notification containing the objectID, then when I receive that notification, I go and find the object that corresponds with the objectID I received.
So in my NSManagedObject subclass, my awakeFromSnapshotEvents looks like this:
- (void)awakeFromSnapshotEvents:(NSSnapshotEventType)flags {
NSManagedObjectID *thisID = self.objectID;
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:thisID forKey:@"noticeObjectID"];
[[NSNotificationCenter defaultCenter] postNotificationName:@"awakeFromSnapshotNotification" object:self userInfo:userInfo];
}
And in the receiver's viewWillAppear, I register for the notification:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didAwakeManagedObject:) name:@"awakeFromSnapshotNotification" object:nil];
Finally, my receiver's didAwakeManagedObject:
method looks like this. There's probably a better way to do this, but this works fine for me. I happen to be concerned about the index position of the object I need within an NSOrderedSet backed by Core Data, so I just iterate through the ordered set til I find the right one.
- (void) didAwakeManagedObject:(NSNotification*)notice {
for (int i=0; i<project.orderedSet.count; i++) {
if ([notice.userInfo objectForKey:@"noticeObjectID"] == [[project.orderedSet objectAtIndex:i] objectID]) {
NSLog(@"%d IS EQUAL", i);
return;
}
}
}
Upvotes: 1