esreli
esreli

Reputation: 5061

Core Data Deletion Unsuccessful *easy fix?*

I have a simple XCDataModel that contains one Entity with One Attribute. Essentially, I am saving a series of Dates.

Now, I Know I am adding the NSDates properly because I run a fetch request after adding them and run through the results like so:

for (NSManagedObject *info in fetchedObjects) {
    NSLog(@"Name: %@", [info valueForKey:@"attribute"]);
}

And every additional NSDate is accounted for. Example from Log:

2012-06-19 12:40:38.531 Arts Days[47194:16103] Name: 2013-03-27 04:00:00 +0000
2012-06-19 12:40:38.531 Arts Days[47194:16103] Name: 2013-03-01 05:00:00 +0000
2012-06-19 12:40:38.532 Arts Days[47194:16103] Name: 2013-01-01 05:00:00 +0000

Now, when I try to delete an object from Core Data, it proves unsuccessful (by running the same fetch and running through the results again).

Here is the fetch:

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Entity" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];

[fetchRequest setFetchBatchSize:366];

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:NO];
NSArray *sortDescriptors = [NSArray arrayWithObjects:sortDescriptor, nil];

NSError *error = nil;

[fetchRequest setSortDescriptors:sortDescriptors];

NSArray *fetchedObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];

for (NSManagedObject *object in fetchedObjects) {
    if ([[object valueForKey:@"date"] isEqualToDate:date]) {
        [managedObjectContext deleteObject:object];
    }
}
if (![managedObjectContext save:&error]) {
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
}

Also, the NSLog with Unresolved error contains nil nil...

Do you know what I am doing wrong?

Upvotes: 0

Views: 96

Answers (1)

gschandler
gschandler

Reputation: 3208

It appears you use two different NSManageObjectContext instances. self.managedObjectContext (an ivar) to set up your fetch request and perform the fetch, but a local instance to do the deleteObject: and save: operations. The local instance managedObjectContext is probably nil and not referring to the same object as the ivar.

Upvotes: 1

Related Questions