iphone - 如何循环遍历 nsfetchedresultscontroller

标签 iphone core-data nsfetchedresultscontroller

在我的应用程序中,我需要循环遍历核心数据中的所有实体,并且我正在使用 NSFetchedresultcontroller。

我现在正在这样做:

NSArray *tempArray = [[NSArray alloc] initWithArray:self.fetchedResultsController.fetchedObjects];

for (MyClass *item in tempArray)
{
    // do something
}

[tempArray release]; tempArray = nil;

有没有更好的方法可以在不创建 tempArray 的情况下做到这一点?

非常感谢

最佳答案

取决于你想做什么。如果您只是更改一个值,那么是的,有一个更简单的方法:

[[[self fetchedResultsController] fetchedObjects] setValue:someValue forKey:@"someKey"]

这将循环遍历所有设置该值的对象。这是标准的 KVC 操作。请注意,这将扩展内存,因为每个实体都会在突变过程中被实现。

如果您需要对每个实体做更多的事情,或者遇到内存问题,那么事情会变得更加复杂。注意:在编码优化阶段之前不要担心内存。内存问题的预优化,尤其是 Core Data 的内存问题,是浪费时间。

这个概念是您将循环每个实体并根据需要更改它。此外,在某个时刻,您应该保存上下文,重置它,然后耗尽本地自动释放池。这将减少内存使用量,因为在拉入下一批之前,您会将刚刚操作的对象从内存中推回。例如:

NSManagedObjectContext *moc = ...;
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSInteger drainCounter = 0;
for (id object in [[self fetchedResultsController] fetchedObjects]) {
  //Do your magic here
  ++drainCounter;
  if (drainCounter = 100) {
    BOOL success = [moc save:&error];
    NSError *error = nil;
    NSAssert2(!success && error, @"Error saving moc: %@\n%@", [error localizedDescription], [error userInfo]);
    [moc reset];
    [pool drain], pool = nil;
    pool = [[NSAutoreleasePool alloc] init];
    drainCounter = 0;
  }
}

BOOL success = [moc save:&error];
NSError *error = nil;
NSAssert2(!success && error, @"Error saving moc: %@\n%@", [error localizedDescription], [error userInfo]);
[pool drain], pool = nil;

这会降低内存使用量,但昂贵!!每 100 个对象就会访问一次磁盘。仅当您确认内存存在问题后才应使用此功能。

关于iphone - 如何循环遍历 nsfetchedresultscontroller,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3512872/

相关文章:

俱乐部中的 iPhone 应用程序分发

ios - 试图理解类型属性,例如 static 和 swift 的 class 关键字

ios - PresentViewController(UIViewController) 不工作

Iphone 应用程序开发 - 如何重新加载(?) View ?

iphone - CoreData 对多对多关系排序

ios - NSFetchedResultsController - 只显示保存在数据库中的结果?

ios - 应用程序突然崩溃,错误显示 : attempt to recursively call -save: on the context in core data

core-data - 在 iOS 中使用 NSPersistentCloudKitContainer 时获取错误堆栈跟踪

core-data - 何时以及多久调用 processPendingChanges 以确保图形完整性

IOS/Xcode/核心数据 : What is equivalent of [[self tableView] reloadData]; when there is no tableview?