gpt4 book ai didi

iphone - 在处理核心数据时如何停止内存的积累?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:48:28 24 4
gpt4 key购买 nike

我已经研究这个问题好几个星期了,我似乎无法解决它。我正在遍历数据库中的每个实体以执行操作。我使用 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++;

}

}

仪器显示:

enter image description here

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

希望有人能帮忙,谢谢。

最佳答案

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

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

使用 NSFetchRequestsetFetchBatchSize: 也会有所帮助。当您从数据存储中请求更多对象时,它会分小批从磁盘中获取对象,而不是一次性获取所有对象。

关于iphone - 在处理核心数据时如何停止内存的积累?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12627256/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com