2

我已经解决这个问题好几个星期了,我似乎无法解决它。我正在遍历数据库中的每个实体以执行操作。我使用 NSFetchRequest 有一段时间了,但尽管我试图阻止它这样做,但它在每次迭代中不断增加内存使用量,显然在每次迭代后没有恢复任何内存。现在我将 NSFetchedResultsController 用于相同的任务。

这是我的代码:

NSFetchedResultsController:

- (NSFetchedResultsController *)updateController {

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

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

    NSSortDescriptor *sort = [[NSSortDescriptor alloc]
                              initWithKey:@"creationDate" ascending:NO];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];

    [fetchRequest setFetchBatchSize:10];

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

    return _updateController;

}

它运行的代码:

    NSLog(@"update controller: %@", [self updateController]);

    if (![[self updateController] performFetch:&error]) {
        // Update to handle the error appropriately.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    }


    int i = 0;

    id  sectionInfo = [[_updateController sections] objectAtIndex:0];

    NSLog(@"count: %i", [sectionInfo numberOfObjects]);

    NSManagedObject *entry;

    while (i < [sectionInfo numberOfObjects]) {

        @autoreleasepool {

            entry = [_updateController.fetchedObjects objectAtIndex:i];

            NSLog(@"entry: %@", [entry valueForKey:@"message"]);

            NSLog(@"context 1: %@", [entry managedObjectContext]);
            NSLog(@"context 2: %@", [[self updateController] managedObjectContext]);

            [[entry managedObjectContext] refreshObject:entry mergeChanges:NO];

            NSLog(@"i: %i", i);

            i++;

        }

    }

仪器显示:

在此处输入图像描述

当我在时间线中单击该时间段时,它会选择表中正在显示的那些条目。图表中执行任务的时间段,数据使用量随着时间的推移而略有增加,从 1.14mb 增加到 1.17mb。在这个阶段这不是很多,但是添加处理更大数据的代码,例如 NSData 图像,意味着应用程序数据使用量会上升,直到它最终耗尽内存并崩溃。该应用程序的 1.0 版本已经在应用程序商店中,因此根本无法在我的核心数据中包含 NSData。

希望有人能帮忙,谢谢。

4

2 回答 2

1

您是否真的尝试将大量对象添加到数据存储中,或者您是否根据您迄今为止基准测试的数据进行推断?Core Data 通常非常擅长管理内存消耗。

当核心数据检测到您不再使用有问题的对象并且内存使用率越来越高时,核心数据会将您的对象重新变为故障并释放所有关联的内存。

使用NSFetchRequest'ssetFetchBatchSize:也会有所帮助。当您从数据存储中请求更多对象时,它将小批量从磁盘中获取对象,而不是一次全部获取。

于 2012-09-28T01:04:58.167 回答
0

您可以在每个要存储大量数据(例如图像)的对象上启用一个选项。它将磁盘上超过 1MB 的任何数据存储在一个文件中;这应该会降低您的内存使用量。

二进制数据文章

于 2012-09-28T00:53:56.693 回答