iPad应用程序
我有一个大文本文件,我想分成几个部分并在循环中处理它们。 我使用了以下代码:
NSArray * contentArray = [stringFromFile componentsSeparatedByString:@" "];
for(...){
contentRange = NSMakeRange(lastPosition , newLength);
NSArray * subContentArray = [contentArray subarrayWithRange:contentRange];
NSString *subContent = [subContentArray componentsJoinedByString:@" "];
....
//Process sub content here...
}
运行后,我收到malloc错误,代码12
观察活动监视器,内存和VM大小增加,直到系统内存耗尽且应用程序崩溃。
有没有办法阻止这种情况?
答案 0 :(得分:2)
解决此问题的一种方法是使用自定义NSAutoreleasePool来不断清除临时分配的内存。像这样:
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSUInteger i=0;
for (...) {
... // your method contents
if (++i % 10 == 0) {
// you might want to play with the frequency of the releases, depending on the size of your loop
[pool release];
pool = [[NSAutoreleasePool alloc] init];
}
}
[pool release];
答案 1 :(得分:0)
自动释放池事物将在很大程度上处理内存问题,但如果文件是任何大小,它可能会很慢。 看起来像是在循环中扫描原始字符串,直接从字符串获取子字符串会更快。还要使用至少1/2的内存,因为您复制了组件数组中的字符串。
代码将在原始字符串上使用rangeOfString,直到找到适当长度的子字符串,然后处理子字符串,然后处理下一个字符串。
iPhone 3G手机仅为您的应用程序提供约5-15 MB的内存。你在iPad上,虽然我看到它确实给你大约4倍的金额。