我正在ARC自动转换项目中工作.
我有一个巨大的文本文件(14MB)的内容存储在NSString *_documentDataString.
现在我有这个循环:
- (void)scanParts
{
NSString *boundary = [boundaryPrefix stringByAppendingString:_header.boundary];
NSMutableArray *parts = [NSMutableArray array];
NSInteger currentLocation = [_documentDataString rangeOfString:boundary].location;
BOOL reachedTheEnd = NO;
while(!reachedTheEnd)
{
NSInteger nextBoundaryLocation = [[_documentDataString substringFromIndex:currentLocation + 1]
rangeOfString:boundary].location;
if(nextBoundaryLocation == NSNotFound)
{
reachedTheEnd = YES;
}
else
{
nextBoundaryLocation += currentLocation + 1;
//[parts addObject:[_documentDataString substringWithRange:
// NSMakeRange(currentLocation, nextBoundaryLocation - currentLocation)]];
currentLocation = nextBoundaryLocation;
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是,我开始收到这些错误:
malloc: *** mmap(size=6496256) failed (error code=12)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug
Run Code Online (Sandbox Code Playgroud)
出了什么问题?
运行此循环时,我甚至开始收到此错误:
while(true)
{
NSInteger nextBoundaryLocation = [[_documentDataString substringFromIndex:currentLocation + 1]
rangeOfString:boundary].location;
}
Run Code Online (Sandbox Code Playgroud)
将substringFromIndex:在
NSInteger nextBoundaryLocation = [[_documentDataString substringFromIndex:currentLocation + 1]
rangeOfString:boundary].location;
Run Code Online (Sandbox Code Playgroud)
创建一个(临时的,自动释放的)子字符串,该子字符串仅在当前自动释放池被销毁时被释放(例如,当程序控制返回到主事件循环时).
您可以用.替换该代码
NSInteger nextBoundaryLocation = [_documentDataString rangeOfString:boundary
options:0
range:NSMakeRange(currentLocation + 1, [_documentDataString length] - (currentLocation + 1))].location;
Run Code Online (Sandbox Code Playgroud)
(希望)避免创建临时字符串.请注意,这nextBoundaryLocation是相对于字符串的开头,所以
nextBoundaryLocation += currentLocation + 1;
Run Code Online (Sandbox Code Playgroud)
没有必要了.
或者,您可以简单地替换完整的循环
NSArray *parts = [_documentDataString componentsSeparatedByString:boundary];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
405 次 |
| 最近记录: |