开发者

Problem with deleting from CoreData

开发者 https://www.devze.com 2023-03-26 00:28 出处:网络
I am using this code for deleting an entry from CoreData: NSManagedObjectContext *context2=[self managedObjectContext];

I am using this code for deleting an entry from CoreData:

        NSManagedObjectContext *context2=[self managedObjectContext];
        NSFetchRequest *fetch2 = [[NSFetchRequest alloc] init];
        NSEntityDescription *entity2=[NSEntityDescription entityForName:@"RecentMovies" inManagedObjectContext:context2];
        [fetch2 setEntity:entity2];
        [fetch2 setResultType:NSDictionaryResultType];
        NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:@"DateTime"];
        NSExpression *minDateExpression = [NSExpression expressionForFunction:@"min:"
                                                    arguments:[NSArray arrayWithObject:keyPathExpression]];
        NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
        [expressionDescription setName:@"minDateTime"];
        [expressionDescription setExpression:minDateExpression];
        [expressionDescription setExpressionResultType:NSDateAttributeType];    
        [fetch2 setPropertiesToFetch:[NSArray arrayWithObject:expressionDescription]];

        error=nil;
        NSArray *objects2 = [context2 executeFetchRequest:fetch2 error:&error];
        if (objects2 == nil) {
            // Handle the error.
            NSLog(@"ERRORS IN SEARCH INSIDE VIEW SUCCESS");
        }
        else {
            if ([objects2 count] > 0) {
                NSLog(@"Minimum date: %@", [[objects2 objectAtIndex:0] valueForKey:@"minDateTime"]);

                //delete the oldest entry !
                for (NSManagedObject *object2 in objects2) {
                    [context2 deleteObj开发者_Go百科ect:object2];
                }

            }
        }

However, I am getting the following error :

Minimum date: 2011-08-03 08:32:35 +0000
2011-08-03 03:33:15.014 EncameoApp[1933:707] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'An NSManagedObjectContext cannot delete objects in other contexts.'

Any help ?

I also have 2 other tables in CoreData and the [self managedObjectContext] is shared between all the CoreData code. I am a little confused here about the error message regarding the context ...


It usually a bad idea to alter the Array you are iterating on.

                for (NSManagedObject *object2 in objects2) {
                [context2 deleteObject:object2];
            }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号