当对核心数据的每个项执行任务时,如何避免耗尽内存? [英] How do i avoid running out of memory when performing a task on every item of core data?

查看:91
本文介绍了当对核心数据的每个项执行任务时,如何避免耗尽内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试执行类似下面的任务:

  NSFetchRequest * request = [NSFetchRequest fetchRequestWithEntityName:@Entry ]; 

NSPredicate * predicate = [NSPredicate predicateWithFormat:@(version ==%@),@1.0];

[request setPredicate:predicate];

NSArray * results = [[AppDelegate applicationDelegate] .managedObjectContext executeFetchRequest:request error:nil];

int i = 0;

while(i< results.count){

Entry * entry = [results objectAtIndex:i];

entry.version = @1.1;

i ++;
}

但是它会在内存溢出之前通过每个结果。 >

我知道这一点:

  [request setFetchBatchSize:20]; 

但我想知道如何与我有什么工作?它会停止处理后20个结果,或者它只是抓住前20个结果,然后以某种方式抓住下一个20并继续?



我要求本质上是如何做

解决方案

这是一个非常有用的数据库,使用 @autoreleasepool



的完美情况在你的循环中执行的所有代码之间放置一个@autoreleasepool。这将在对象经过处理后自动释放,因此您的内存占用量保持较低。



有关详细信息,请参阅苹果文档;



https://developer.apple .com / library / mac / documentation / Cocoa / Conceptual / MemoryMgmt / Articles / mmAutoreleasePools.html


I'm trying to perform a task similar to this:

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Entry"];

        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(version == %@)", @"1.0"];

        [request setPredicate:predicate];

        NSArray *results = [[AppDelegate applicationDelegate].managedObjectContext executeFetchRequest:request error:nil];

int i = 0;

        while (i < results.count) {

            Entry *entry = [results objectAtIndex:i];

            entry.version = @"1.1";

            i++;
        }

But it runs out of memory before it's got through every result.

I'm aware of this:

[request setFetchBatchSize:20];

But I'm wondering how that would work with what I have? Would it stop processing after 20 results, or would it just grab the first 20 results then somehow grab the next 20 and continue?

What i'm asking essentially is how do i only grab a certain amount of data, to stop it running out of memory, then grab another batch?

解决方案

This is a perfect case for using an @autoreleasepool

Place an @autoreleasepool around all the code which gets executed in your loop. This will automatically release the objects after they get processed so your memory footprint stays low. If using this technique you shouldn't have to specify a batch size.

See the apple docs here for more information;

https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmAutoreleasePools.html

这篇关于当对核心数据的每个项执行任务时,如何避免耗尽内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆