【问题标题】:Core Data deleteObject: not working?核心数据删除对象:不工作?
【发布时间】:2012-12-21 12:34:32
【问题描述】:

我正在使用以下代码:

+(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 打印对象,它返回了正确的对象,但该对象仍然没有从我的核心数据模型中永久删除。 我的实体与其他实体都没有关系。

谁能解释一下怎么回事?

谢谢。

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

【问题讨论】:

    标签: iphone ios core-data


    【解决方案1】:

    在您保存之前,您对 NSManagedObjectContext 所做的任何更改都是暂时的。尝试将其添加到方法的末尾:

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

    【讨论】:

      【解决方案2】:

      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();
              } 
          }
      }
      

      【讨论】:

      • 谢谢...我明白了。
      猜你喜欢
      • 1970-01-01
      • 2016-10-27
      • 2012-06-17
      • 2016-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-23
      相关资源
      最近更新 更多