undo all changes made in the child view controller

前端 未结 1 1727
旧时难觅i
旧时难觅i 2020-12-28 10:27

There are two entities: Author and Book. Author has an attribute authorName and a to-many relationships books. Book has several attributes and a relationship author. There i

相关标签:
1条回答
  • 2020-12-28 10:33

    Several things to consider. First, in a scenario like this, I would use a separate MOC instead of the undo manager. Namely, I'd do something like this (assuming ARC - you can do the mapping if necessary)...

    You must have some other code providing the book to the VC through a setter, since you access it in viewDidLoad. I'd change viewDidLoad to something like this...

    -(void)viewDidLoad
    {
        self.managedObjectContext = [[NSManagedObjectContext alloc] init];
        self.managedObjectContext.parentContext = self.book.managedObjectContext;
        // We are in the main thread, so we can safely access the main MOC
        // Basically, move our object pointer to book into our local MOC.
        NSError * error = nil;
        Book *book = [self.managedObjectContext existingObjectWithID:self.book.objectID error:&error];
        // handle nil return and/or error
        self.book = book;
        // Now, your access to book will be in the local MOC, and any changes
        // you make to the book or book.author will all be confined to the local MOC.
    }
    

    Now, all you have to do is call

    [self.managedObjectContext save:&error];
    

    in your saveAndDismiss action. If you don't call save, none of the changes will be saved, they will all just automatically disappear.

    EDIT

    Note, that the above "save" just moves the object state into the parent context. So, the "main" MOC now has the changes from the "child" but none of the changes have been saved to disk yet.

    0 讨论(0)
提交回复
热议问题