【问题标题】:how to loop through nsfetchedresultcontroller如何循环通过nsfetchedresultscontroller
【发布时间】:2010-08-18 13:59:25
【问题描述】:

在我的应用程序中,我需要遍历 Core Data 中的所有实体,并且我正在使用 NSFetchedresultcontroller。

我现在正在这样做:

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

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

[tempArray release]; tempArray = nil;

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

非常感谢

【问题讨论】:

    标签: iphone core-data nsfetchedresultscontroller


    【解决方案1】:

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

    [[[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 个对象后你就会访问磁盘。这只能在您确认内存存在问题后使用。

    【讨论】:

      【解决方案2】:

      对不起,我认为答案很明显:

              for (MyClass *item in self.fetchedResultsController.fetchedObjects)
              {
                  //do something
              }
      

      这是记忆方面的好方法吗?

      【讨论】:

        猜你喜欢
        • 2015-07-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-20
        • 1970-01-01
        • 2011-07-04
        相关资源
        最近更新 更多