我正在使用此代码删除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 deleteObject:object2];
}
}
}
但是,我收到以下错误:
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.'
有任何帮助吗?
我在CoreData中还有另外两个表,并且[self managedObjectContext]在所有CoreData代码之间共享。关于上下文的错误消息,我在这里有点困惑......
答案 0 :(得分:0)
改变你正在迭代的数组通常是一个坏主意。
for (NSManagedObject *object2 in objects2) {
[context2 deleteObject:object2];
}