遍历数组并从核心数据中获取数据

3
我有一个包含200个数字(物品ID)的数组,我想使用每个物品的物品ID从核心数据中获取一些数据。 我假设唯一的方法是在循环内查询核心数据,每次执行fetchRequest并将结果添加到可变数组中。 这似乎会占用大量内存,并且循环遍历200个项可能不是获取所需数据的最佳方式。
所有这些数据的目的地都是一个表格,因此我想使用NSFetchedResultsController,但这可能要求过高。
当您有数百个项需要查询时,从核心数据检索数据的最佳方法是什么?
非常感谢提供示例代码。
以下是我的代码:
- (NSFetchedResultsController *)fetchedResultsController {

if (_fetchedResultsController != nil) {
    return _fetchedResultsController;
}

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription 
                               entityForName:@"Shows" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];

NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"downloadCount" ascending:NO];

[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"showId IN %@", resultsArray];
[fetchRequest setPredicate:predicate];

[fetchRequest setFetchBatchSize:20];

NSFetchedResultsController *theFetchedResultsController = 
[[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest 
                                    managedObjectContext:managedObjectContext 
                                      sectionNameKeyPath:nil 
                                               cacheName:nil];

self.fetchedResultsController = theFetchedResultsController;
_fetchedResultsController.delegate = self;

[sort release];
[fetchRequest release];
[theFetchedResultsController release];

return _fetchedResultsController;    

}
1个回答

5
最好使用谓词。例如:
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

// Set the entity for the fetch request.
NSEntityDescription *entity = [NSEntityDescription entityForName:@"EntityName" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"myID IN %@", IDArray];

// Set the predicate for the fetch request.
[fetchRequest setPredicate:predicate];

// Perform the fetch.
NSError *error;
NSArray *array = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
[fetchRequest release];

这只是一个粗略的示例,因为我不知道您的ID形式或核心数据中有什么,但基本上您可以仅搜索存储在数组中的ID的核心数据,并且如果需要,可以进一步实现谓词以仅返回某些值。这应该至少能让您开始。


我所遗漏的是 @"myID IN %@", IDArray,但是尽管我知道IDArray有200个条目,fetchRequest没有返回任何值,我仍然遇到一个问题。我将我的代码添加到问题中。 - Michael Morrison
我已经考虑过了。我想我可以默认加载旧数据,在ViewDidLoad中进行JSON请求,并在requestFinished中重新加载tableView。现在我正在使用XML更新应用程序的其余数据,并考虑将所有更新过程(其中之一就是这个)切换到JSON...但我讨厌不得不更新所有那些代码。至少它会更加一致,可能也更有效率。如果我转移到JSON,我可以在应用程序委托中完成所有其他更新,并在到达此特定页面时仅更新模型并查询核心数据。 - Michael Morrison
可以使用两个数组和两个键路径来使用IN运算符吗? - jjxtra
@PsychoDad 是的,那是可能的。你只需要设置你的谓词,就像下面这样:NSPredicate *myPred = [NSPredicate predicateWithFormat:@"key1 IN %@ AND key2 IN %@", array1, array2]。你只需将谓词拆分为布尔语句即可。 - justin
@PsychoDad,您介意给出一个您想要实现的简短示例吗?恐怕我可能无法完全理解,并且不想给您提供任何错误信息。另外,非常抱歉让您等了这么久。 - justin
显示剩余7条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接