Search code examples
core-datansmanagedobjectnsmanagedobjectcontext

Do I need to call NSManagedObjectContext deleteObject


You know how when you generate a class from an NSManagedObject, and it creates the CoreDataGeneratedAccessors for you...

@interface SomeManagedObject (CoreDataGeneratedAccessors)

- (void)addBookmarkObject:(Bookmark *)value;
- (void)removeBookmarkObject:(Bookmark *)value;
- (void)addBookmark:(NSSet *)values;
- (void)removeBookmark:(NSSet *)values;

Well it seems redundant to have to call...

[someManagedObject removeBookmarkObject:myBookmark]

followed by ....

[managedObjectContext deleteObject:myBookmark]

Why doesn't the removeBookmarkObject make the call to deleteObject for me, if it is in fact needed? Who would want to 'partially' delete an object from their database??

What am I missing about this?


Solution

  • Just because you remove a Bookmark from the relationship, that doesn't necessarily mean you want it deleted: it might be perfectly valid to have a Bookmark which isn't (currently) related to any objects. Suppose for example that SomeManagedObject was a ShoppingBasket, and Bookmark was ShoppingItem - would you want to delete a ShoppingItem from your shop, just because someone removed it from their ShoppingBasket?

    But the reverse isn't true: if you delete a Bookmark, you mustn't leave any Objects related to it. Bad things can (and generally will) happen. Consequently, CoreData provides a mechanism (see "Relationship Delete Rules" in the Core Data Programming Guide) to automatically deal with related objects when you delete the source object. So if the relationship is configured with your desired delete rule, you could just use:

    [managedObjectContext deleteObject:myBookmark]
    

    and CoreData will sort out the relationships. (For example, if you specified a "nullify" delete rule, it would effectively call

    [someManagedObject removeBookmarkObject:myBookmark]
    

    for all the managedObjects related to myBookmark.)