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