0

我在 iPhone 应用程序中遇到了内存问题,这让我很难受。这是我收到的错误消息:

malloc: * mmap(size=9281536) failed (error code=12) * error: can't allocate region

我正在为这个应用程序使用 ARC,以防这可能是有用的信息。代码(如下)只是使用 Bundle 中的文件来加载核心数据实体。

奇怪的是,崩溃只发生在 90 多个循环之后;虽然看起来,由于“内容”的大小越来越小,内存请求也应该越来越小。

这是代码,如果有人可以看到缺陷,请告诉我。

NSString *path,*contents,*lineBuffer;
path=[[NSBundle mainBundle] pathForResource:@"myFileName" ofType:@"txt"];
contents=[NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];

int counter=0;

while (counter<10000) {
    lineBuffer=[contents substringToIndex:[contents rangeOfCharacterFromSet:[NSCharacterSet newlineCharacterSet]].location];
    contents=[contents substringFromIndex:[lineBuffer length]+1];
    newItem=[NSEntityDescription insertNewObjectForEntityForName:@"myEntityName"
                                                      inManagedObjectContext:context];
    [newItem setValue:lineBuffer forKey:@"name"];

    request=[[NSFetchRequest alloc] init];
    [request setEntity: [NSEntityDescription entityForName:@"myEntityName"
                         inManagedObjectContext:context]];
    error=nil;
    [context save:&error];

    counter++;
}
4

1 回答 1

1

我终于解决了使用 NSMutableString 而不是 NSString 作为内容的问题。然后使用:[contents deleteCharactersInRange:range]; 当然,保持足够的范围。循环内。

于 2012-10-17T04:59:14.793 回答