【问题标题】:Programmatically update duplicate values in coredata?以编程方式更新 coredata 中的重复值?
【发布时间】:2012-09-06 06:13:58
【问题描述】:

我是 Core Data 的新手。我想更新重复值。例如我的表是这样的

 id | Name
============
 1  | Joseph  
 2  | Fernandez  
 3  | Joseph
 4  | James

假设我想将 id 1 和 4 对应的 Joseph 更新为“myName”。当我尝试更新它时,它只更新第 4 行。我在任何文档中都找不到任何方法来做到这一点。谁能给我一个解决方案?

还有一个问题,如何打印所有名称值?

【问题讨论】:

    标签: ios xcode core-data


    【解决方案1】:

    您必须阅读文档才能知道如何更新记录 http://www.appcoda.com/core-data-tutorial-update-delete/

    【讨论】:

      【解决方案2】:

      詹姆斯,

      我将尝试用示例代码回答您的两个问题。

      要更新特定对象,您需要使用谓词设置新的NSFetchRequest,获取对象(NSManagedObject 类型),更新您感兴趣的值并保存上下文。

      所以,例如:

      NSFetchRequest* fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"YourEntityName"];
      // set the predicate (it's equal to set a WHERE SQL clause) filtering on the name for example
      // use camel case notation if possible, so instead of Name use name (for this you have to changes your model, if you don't want to do it use Name)
      [fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"name == %@", @"Joseph"]];
      
      NSError* error = nil;
      NSArray* results = [context executeFetchRequest:fetchRequest error:&error];
      // do some error checking here...
      for (NSManagedObject resultItem in results) {
      
          // use KVC (for example) to access your object properties
          [resultItem setValue:@"myName" forKey:@"name"];
      }
      
      // save your context here
      // if you don't save, changes are not stored
      

      要打印,您需要设置一个新的NSFetchRequest,抓取对象(NSManagedObject 类型)并使用NSLog

      例如:

      NSFetchRequest* fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"YourEntityName"];
      
      NSError* error = nil;
      NSArray* results = [context executeFetchRequest:fetchRequest error:&error];
      // do some error checking here...
      for (NSManagedObject resultItem in results) {
      
          NSLog(@"%@", [resultItem valueForKey:@"name"]);
      }
      

      附:我提供的代码非常简单,我用于特定值的谓词检查name。由于这可能容易出错,我会修改模型并为您需要使用的每个对象使用一种guid(我不知道 id 是否适用,但我会将其名称更改为另一个名称,例如userId)。完成后,您可以对其进行检查。

      希望对您有所帮助。

      【讨论】:

        【解决方案3】:

        就像检索NSManagedObject 并更改Name 属性一样简单。您可以使用 fetch 请求检索 NSManagedObject。更改属性后,即使关闭应用程序也希望保持更改,您必须在 managedObjectContext 上执行 save

        您必须通读文档才能快速了解核心数据: http://developer.apple.com/library/mac/#documentation/cocoa/Conceptual/CoreData/Articles/cdBasics.html#//apple_ref/doc/uid/TP40001650-TP1

        编辑:只需NSLog 任何您想知道的信息,例如记录您获取请求结果。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-07-07
          • 1970-01-01
          • 2018-06-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多