Theo
Theo

Reputation: 1261

CoreDataGeneratedAccessors to remove object don't seem to be deleting

I have an NSManagedObject that has a to-many relationship to another NSManagedObject.

During creation of the NSManagedObject I can use the generated accessors 'removeNotesObject' and the deletion works fine. I can create an object to add to the parent object, save the object, delete the object and then save again. When I fetch this parent object the object I created and deleted is still deleted.

However, after I add the object and then save it (but don't delete and save after) and then fetch it, I can't seem to delete the object that was previously created. I am using the generated accessors to try and remove the object, which appears to work but when I fetch it again the object hasn't been deleted.

(Note: Adding objects does work so it is not a problem with the saving)

To delete the object I retrieve the set of object and select the objects I want to delete. Then I remove the objects

NSSet *notes = summary.notes;
NSSet *oldNotes = [notes objectsPassingTest:^(id obj,BOOL *stop){
    Note *oldNote = (Note *)obj;
    BOOL sameRow = (oldNote.row == newNote.row);
    BOOL sameColumn = (oldNote.column == newNote.column);
    BOOL success = (sameRow && sameColumn);
    return success;}];
[summary removeNotes:oldNotes];

I have tried making the relationship inverse to delete the objects which didn't delete them. I have also tried different delete rules (cascade and nullify) which again didn't work. Finally, I tried to remove each object separately and deleting each object from the context after I had removed it from the parent object which again unfortunately didn't work.

I assume the problem must be something to do with it being a fetched object. If anyone could help I would really appreciate it as I can't think of any other ways to test or solve this problem.

Upvotes: 3

Views: 637

Answers (2)

Theo
Theo

Reputation: 1261

The reason the above code did not work is that == will not actually compare the NSNumber. Instead you need to call 'isEqualTo:'. I think before it was checking the address hence working before I saved it. What's more it was returning an object in the NSSet so appeared to be working. During debugging it wasn't clear what the object was but clearly wasn't the one I needed.

Upvotes: 0

lorean
lorean

Reputation: 2150

You need to do

NSManagedObjectContext * moc = .......;
[moc deleteObject:note]

edit: The core data generated accessors simply remove the object from the relationship, but do not delete the object permanently. This makes sense because you may have one NSManagedObject associated to multiple other NSManagedObjects via relationships.

edit: Deleting in the above mentioned fashion will invoke the deletion rules. I suggest you double check that they are setup correctly.

Upvotes: 1

Related Questions