【问题标题】:Loading all the values of an attribute of core data to an array将核心数据的某个属性的所有值加载到数组中
【发布时间】:2026-02-12 02:45:01
【问题描述】:

我有一个属性“term”,它是我的核心数据“Event”中的一个 NSString。 加载表格视图时,我希望将“名称”的所有值加载到数组中。

我使用了代码

- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
      Event   *event  = nil;
      event = [fetchedResultsController objectAtIndexPath:indexPath];
    if(searching){
        cell.textLabel.text = [copyListOfItems objectAtIndex:indexPath.row];
    }else{   
          if(event.term){ 
                [listOfItems addObject:event.term]; 
         }
          cell.textLabel.text = event.term;
          cell.detailTextLabel.text = event.definition;
      }
}

问题是所有术语都没有加载到 NSMutableArray listOfItems 中。它在表格单元格滚动到底部时加载。

如何将核心数据中“term”的所有内容加载到数组listOfItems中。

任何帮助将不胜感激。

【问题讨论】:

    标签: iphone objective-c cocoa-touch xcode core-data


    【解决方案1】:

    您很可能对 Core Data 的看法是错误的。 Core Data 不是数据库。它是一个碰巧持久化到数据库的对象图。话虽如此,您的问题最好问为“我如何加载实体 'Event' 的所有实例并访问其 term 属性”。

    为此,您希望构建并执行一个NSFetchRequest 针对没有谓词的“事件”实体。

    NSManagedObjectContext *moc = ...;
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:[NSEntityDescription entityForName:@"Event" inManagedObjectContext:moc]];
    NSError *error = nil;
    NSArray *events = [moc executeFetchRequest:request error:&error];
    NSAssert2(events != nil && error == nil, @"Error fetching events: %@\n%@", [error localizedDescription], [error userInfo]);
    

    然后您可以从这里使用“KVC”来检索名称属性的数组:

    NSArray *namesArray = [events valueForKey:@"name"];
    

    这将产生一个仅填充该字符串的数组。

    但是更好的问题是,如果要在表格中显示所有内容,为什么还需要数组? NSFetchedResultsController 已经为您检索到所有“事件”实体;它只是绑定到表格的显示器。你的目标是什么?

    更新

    非常感谢马库斯先生的详细回答...我的目标是使用搜索栏从核心数据中搜索特定的“术语”。有没有更好的方法来做到这一点?

    是的,有很多解决方案。您可以使用现有NSFetchedResultsController-fetchedObjects 属性访问所有结果。从那里您可以通过使用-filteredArrayUsingPredicate: 对该数组应用NSPredicate 来获得过滤后的数组,然后您可以在搜索结果中使用该数组。

    如果您在 SO 上搜索 Core Data 和 UISearchDisplayController,我怀疑您会找到很多结果和建议。

    【讨论】:

    • 非常感谢马库斯先生的详细回答...我的目标是使用搜索栏从核心数据中搜索特定的“术语”。有没有更好的方法来做到这一点?
    • 那么,谁在我的答案下标记了我的答案,甚至没有评论为什么?
    • +1 @Marcus S. Zarra -- 哈!有些人在核心数据问题上用石头标记你。可能是意外。