2011-08-03 51 views
0

刪除我使用這個代碼刪除從CoreData的條目:問題與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中還有2個其他表,並且[self managedObjectContext]在所有CoreData代碼之間共享。我在這裏對關於上下文的錯誤信息有點困惑......

回答

0

通常改變你正在迭代的數組是一個壞主意。

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

不知道你的意思,我沒有改變陣列,其中1是對象2,另一種是objects2 ...他們是不一樣的名字......:-s – ahsan

+0

對象2是object2中的一個對象,然後繼續刪除object2,從而更改objects2數組。問題出現在循環中,因爲object2被取出而另一個object2取代了它的位置,改變了快速枚舉器使用的[objects count]值。 – RickiG

+0

那麼你有什麼建議? – ahsan