1
votes

I'm having trouble deleting records from Core Data SQLite file. I want to be able to delete the corresponding record from my file when I delete a row from my table view.

Here is what I am doing after fetching all records into allContacts array

NSManagedObject *contactRecord = [allContacts objectAtIndex:arc4random() % allContacts.count];
self.managedObjectID = [contactRecord objectID];

Then called my method that prepares my contacts and then display them on the tableview.

When I delete a row from the table, I call this method

-(void)deleteContactFromFile:(contact *)deletedContact
{
    NSLog(@"deleted Contact %@",deletedContact.personID);
    AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *context = appDelegate.managedObjectContext;
    [context deleteObject:[context objectWithID:self.managedObjectID]];
    [context save:nil];
}

The funny thing is I get a random record deleted from my core data file, but not the one I selected. I don't know how to deal with ObjectID thing for deleting a specific NSManagedObject.

If my question is not clear enough please tell me to clarify more.

2
"i get a random record deleted from my core data file, but not the one i selected". But you're selecting one at random! Your first code snippet uses arc4random to choose the one that you later delete. If you're selecting one at random, how is deleting one at random not what you expect?Tom Harrington

2 Answers

1
votes

You should be using an NSFetchedResultsController. It will help you to associate every index path of your table view with a specific managed object. You then do not need to fetch all data and filter through them.

For example, if you have the index path and a fetched results controller it is as easy as

NSManagedObject *object = [self.fetchedResultsController objectAtIndexPath:indexPath];
NSManagedObjectContext *context = object.managedObjectContext;
[context deleteObject:object]; 
[context save:nil]; 

Note that you not need to go to your app delegate to get the managed object context.

-1
votes

Try this:

- (void)deleteContactFromFile:(contact *)deletedContact {
    NSManagedObjectContext *context = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
    NSFetchRequest *fetchRequest = [NSFetchRequest new];
    [fetchRequest setEntity:[NSEntityDescription entityForName:@"EntityName" inManagedObjectContext:context]];
    NSError *error;
    NSArray *rootArray = [context executeFetchRequest:fetchRequest error:&error];
    for (NSManagedObject *object in rootArray) {
        if ([context objectWithID:self.managedObjectID]) {
            [context deleteObject:object];
        }
    }
}