0
votes

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?

1
If that is all your code, then you never actually performed the fetch with your fetchRequest and fetchObjects is empty (nil, really).gschandler
I left that line out by accidentesreli
have you debugged the code? is it executing as expected?Dima
It builds with no errors or warnings. It executes not as expected, because the object just doesn't delete.esreli
I noticed everywhere else in the code you use self.managedObjectContext, except where you call deleteObject and save:. Could it be you are using a local instance that is not valid (nil)?gschandler

1 Answers

1
votes

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.