2012-12-21 62 views
5

我使用下面的代码:核心数据deleteObject:不工作?

+(void)deleteObject:(NSManagedObjectID*)oId { 
NSError *error; 
DFAppDelegate *temp = [DFAppDelegate new]; 
NSManagedObjectContext *context = [temp managedObjectContext]; 
NSManagedObject *obj = [context existingObjectWithID:oId error:&error]; 
[context deleteObject:obj]; 
} 

但它似乎并没有相应的工作。当我在iOS模拟器上重新启动应用程序时,我可以在列表中再次看到对象。 我试图用给定的对象ID打印对象,它正在返回正确的对象,但仍然不会永久删除该对象形成我的核心数据模型。 我的实体没有一个与另一个实体有关系。

任何人都可以解释我有什么问题吗?

谢谢。

编辑: 我检查了错误,但没有显示错误。

回答

17

NSManagedObjectContext所做的任何更改都是暂时的,直到您保存为止。尝试添加给你的方法结束:

if (![context save:&error]) { 
    NSLog(@"Couldn't save: %@", error); 
} 
+0

谢谢...代码现在工作.... –

3

NSManagedObjectContext提供了一个便签:你可以做任何你与你喜欢的对象,但需要将其保存在最后。如果您使用的是默认核心数据项目,看看这个方法在你AppDelegate

- (void)saveContext 
{ 
    NSError *error = nil; 
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext; 
    if (managedObjectContext != nil) { 
     if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) { 
      // Replace this implementation with code to handle the error appropriately. 
      // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
      NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 
      abort(); 
     } 
    } 
} 
+0

谢谢...我得到的概念。 –