核心数据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打印对象,它正在返回正确的对象,但仍不会永久删除对象形成我的核心数据模型。 我的实体没有一个与另一个实体有关系。

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

谢谢。

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

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

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

NSManagedObjectContext提供了一个便笺簿:你可以对你的对象做任何你喜欢的事情,但是最后需要保存它。 如果您使用的是默认的Core Data项目,请在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(); } } }