2014-03-25 180 views
-1

我試圖刪除核心數據實體中的所有對象。
我試着用下面的代碼,但不斷收到此錯誤:刪除核心數據中的對象

'An NSManagedObjectContext cannot delete objects in other contexts.' 

下面是代碼:

- (NSManagedObjectContext *)managedObjectContext { 
    NSManagedObjectContext *context = nil; 
    id delegate = [[UIApplication sharedApplication] delegate]; 
    if ([delegate performSelector:@selector(managedObjectContext)]) { 
     context = [delegate managedObjectContext]; 
    } 
    return context; 
} 


- (void) deleteObjects { 

    NSManagedObjectContext *managedObjectContext = [self managedObjectContext]; 
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Fixture"]; 

    NSError *error; 
    NSArray *array = [managedObjectContext executeFetchRequest:fetchRequest error:&error]; 
    if (array == nil) { 
     NSLog(@"Error"); 
    } else { 
     NSManagedObject *funFixture = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy]; 
     [managedObjectContext deleteObject:funFixture]; 
    } 


} 
+0

你[看這三個問題(http://stackoverflow.com/search?q=%22cannot+delete+objects+in+other+contexts%22)? – dasblinkenlight

回答

1

你的問題就在這裏:

NSManagedObject *funFixture = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy]; 

您已經已經執行了fetchRequest,並且你有array中的對象。您需要刪除這些對象,而不是重新運行execute。事情是這樣的:

for (NSManagedObject* object in array) { 
    [managedObjectContext deleteObject:object]; 
} 
相關問題