【问题标题】:CoreData: How to fetch a specific object using a predicateCoreData:如何使用谓词获取特定对象
【发布时间】:2011-01-19 08:28:27
【问题描述】:

情况:

我从我的 sqllite 核心数据数据库中获取一个完整的表,并在 TableView 中显示它,如下所示:

NSEntityDescription *entity = [NSEntityDescription entityForName:@"MyTable"
                                          inManagedObjectContext:managedObjectContext];

挑战:

我如何获取 EntryID 并从数据库中获取特定条目(例如,如果我单击一个条目)?我认为这是朝着正确的方向发展?

NSPredicate *predicate = [NSPredicate predicateWithFormat: @"(id = %@)", myEntryID];

【问题讨论】:

    标签: objective-c iphone core-data


    【解决方案1】:

    这是正确的谓词:

    [NSPredicate predicateWithFormat:@"SELF = %@", objectID];
    

    其中objectIDNSManagedObjectID 实例。

    【讨论】:

      【解决方案2】:

      如果你有一个名为entry 的入口对象,它会是这样的谓词:

      NSPredicate *predicate = [NSPredicate predicateWithFormat: @"(SELF = %@)", entry];
      

      大致相当于

      NSPredicate *predicate = [NSPredicate predicateWithFormat: @"(objectID = %@)", entry.objectID];
      

      对于NSManagedObjectID,您会得到如下信息:

      NSPredicate *predicate = [NSPredicate predicateWithFormat: @"(objectID = %@)", myEntryID];
      

      【讨论】:

      • +1 如果您必须使用谓词,这就是要走的路。否则,-[NSManagedObjectContext objectWithID:] 可能会更好。
      • 当然,但是对于例如NSFetchedResultsController 你必须使用谓词。
      • “self”关键字也适用于每个对象 ID 获取 多个 对象:NSPredicate *predicateForFetch = [NSPredicate predicateWithFormat:@"(self IN %@)", arrayOfNSManagedObjectIDs];
      • 如果我使用objectID,我会得到NSInvalidArgumentException', reason: 'keypath objectID not found in entity <NSSQLEntity Report id=7>'
      • @Benjohn 我得到了相同的结果,但您可以将 SELF 与 objectID 进行比较。 [NSPredicate predicateWithFormat: @"(SELF = %@)", objectID];
      【解决方案3】:

      当您构建表时,您可以使用 fetch 返回的数组或 NSFetchResultsController 中的隐式数组。因此,您想要的对象在数组/控制器中的索引与在表中的索引相同。

      所以,这只是一个调用的问题:

      myObject=[fetchedArray objectAtIndex:tableRowIndex];
      

      myObject=[myFetchedResultsController objectAtIndexPath:tableRowIndex];
      

      这是 UITable 的真正天才之处。它总是准确地反映数据模型。您永远不必在表索引和数据模型索引之间来回转换。

      【讨论】:

        【解决方案4】:

        您可能想查看-[NSManagedObject objectID]-[NSManagedObjectContext objectWithID:]

        【讨论】:

          猜你喜欢
          • 2013-10-24
          • 1970-01-01
          • 2014-10-15
          • 2021-08-22
          • 1970-01-01
          • 1970-01-01
          • 2017-05-09
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多