I have a questions relate with Core Data and the remove object functions that are created automatically when a NSManagedObject subclass is created for a certain entity. I have to entities; one called Label, with one relationship called artists, and another entity called Artist, which has one relationship called label. the artists relationship destination is the entity Artist with an inverse relationship set to label.
I'm added several "Artist" with the same name (Freekey Zekey) and I'm trying to delete them using the next code
NSError *error = nil;
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
// Grab the artist and delete
Artist *freekey = [fetchedObjects objectAtIndex:0];
[freekey.label remove ArtistsObject:freekey];
// Save everything
if([context save:&error])
{
NSLog(@"The save was successful!");
}
else
{
NSLog(@"The save wasn't successful: %@", [error localizedDescription]);
}
After executing this code, I read the data but the artist is only deleted when I have just one "Freekey Zekey". However when I run the app again the number of objects in fetchedObjects is still one. If I have more than one "Freekey Zekey" I expect just one to be removed but it doesn't happen.
I tried using this code to delete all the "Freekey Zekey"
for(int i=0; i < [fetchedObjects count]; i++)
{
freekey = [fetchedObjects objectAtIndex:i];
[freekey.label remove ArtistsObject:freekey];
}
And it works but when I check the numbers of objects in fetchedObjects it's not 0 which, I believe, means the objects haven't been removed.
How can I completely delete an object?
The answer is: You do not completely remove artists from DB. You just removed relationship and to accomplish deletion you need to delete the artists too.
for(int i=0; i < [fetchedObjects count]; i++)
{
freekey = [fetchedObjects objectAtIndex:i];
[freekey.label removeArtistsObject:freekey];
[context deleteObject:freekey];
}
if([context save:&error])
{
NSLog(@"The save was successful!");
}
else
{
NSLog(@"The save wasn't successful: %@", [error localizedDescription]);
}
Hope it helps.
Apple docs are not really clear in this. The general method is as Apple advised:
Data *lastData = [[self sortedPersonDatas] objectAtIndex:0];
[selectedPerson removePersonDataObject:lastData];
where PersonData is a one-to-many relationship to Data managed object from I took the last data (lastData resulted from a sorted array of all data) But using the factory remove methods and checking the SQL database behind we can find that the actual data is existing just the inverse relationship is null. To completely delete the data (all attributes and the object) you had to use:
[selectedPerson.managedObjectContext deleteObject:lastData];
this will completely remove the records as you save context. The correct documentation from Apple
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With