Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Core Data deleteObject: not working?

I'm using the following code:

+(void)deleteObject:(NSManagedObjectID*)oId {
NSError *error;
DFAppDelegate *temp = [DFAppDelegate new];
NSManagedObjectContext *context = [temp managedObjectContext];
NSManagedObject *obj = [context existingObjectWithID:oId error:&error];
[context deleteObject:obj];
}

But it doesn't seem to work accordingly. When I restart my application on iOS simulator I can see the object again in the list. I've tried to print the object with the given object id and it is returning the correct object but still the object is not deleted permanently form my core data model. None of my entity is in relationship with another entity.

Can anyone explain me what's going wrong?

Thanks.

EDIT: I've checked for error, but it shows no error.

like image 854
Aditya Mathur Avatar asked Dec 21 '12 12:12

Aditya Mathur


2 Answers

Any changes that you make to a NSManagedObjectContext are temporary until you save it. Try adding this to the end of your method:

if (![context save:&error]) {
     NSLog(@"Couldn't save: %@", error);
}
like image 60
Jesse Rusak Avatar answered Oct 09 '22 01:10

Jesse Rusak


The NSManagedObjectContext provides a scratch-pad: you can do whatever you like with your objects, but need to save it at the end. If you're using the default Core Data project, look at this method in your AppDelegate:

- (void)saveContext
{
    NSError *error = nil;
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
             // Replace this implementation with code to handle the error appropriately.
             // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        } 
    }
}
like image 27
nikolovski Avatar answered Oct 09 '22 00:10

nikolovski