创建一个长NSString导致内存问题

top*_*ace 3 iphone nsstring

我下面的代码导致我的应用程序退出,即获取黑屏,然后在调试器控制台中看到:程序收到信号:"0".

基本上,当我的orderArray计数为2000或更多时,它会导致问题.我在iOS 4.2上使用iPhone 3GS

问题:创建我的long outStr是否有更高效,耗费更少内存的方法?

NSString *outStr = @"";

for (int i = 0; i < count; i++) {
    NSDictionary *dict = [[ARAppDelegate sharedAppDelegate].orderArray objectAtIndex:i];
    outStr = [outStr stringByAppendingFormat:@"%@,%@,%@,%@\n", 
              [dict valueForKey:@"CODE"], 
              [dict valueForKey:@"QTY"],
              [[ARAppDelegate sharedAppDelegate].descDict valueForKey:[dict valueForKey:@"CODE"]],
              [[ARAppDelegate sharedAppDelegate].priceDict valueForKey:[dict valueForKey:@"CODE"]]];

}
Run Code Online (Sandbox Code Playgroud)

更新:感谢非常善良的人帮助,下面是我修改后的代码:

NSArray *orderA = [ARAppDelegate sharedAppDelegate].orderArray;
NSDictionary *descD = [ARAppDelegate sharedAppDelegate].descDict;
NSDictionary *priceD = [ARAppDelegate sharedAppDelegate].priceDict;
NSMutableString *outStr = [[[NSMutableString alloc] init] autorelease];
for (int i = 0; i < [orderA count]; i++) {
    NSDictionary *dict = [orderA objectAtIndex:i];
            NSString *code = [dict valueForKey:@"CODE"];
    [outStr appendFormat:@"%@,%@,%@,%@\n", 
              code, 
              [dict valueForKey:@"QTY"],
              [descD valueForKey:code],
              [priceD valueForKey:code]];
}


[self emailTxtFile:[NSString stringWithString:outStr]]; 
Run Code Online (Sandbox Code Playgroud)

//这到达方法的结尾

mvd*_*vds 5

问题是在每次迭代中都会形成一个新的字符串对象.这会消耗大量内存.一种解决方案可能是使用本地自动释放池,但这里相当复杂.

你应该使用NSMutableString,如:

NSMutableString *outStr = [[[NSMutableString alloc] init] autorelease];
for (int i = 0; i < count; i++) {
    NSDictionary *dict = [[ARAppDelegate sharedAppDelegate].orderArray objectAtIndex:i];
    [outStr appendFormat:@"%@,%@,%@,%@\n", 
          [dict valueForKey:@"CODE"], 
          [dict valueForKey:@"QTY"],
          [[ARAppDelegate sharedAppDelegate].descDict valueForKey:[dict valueForKey:@"CODE"]],
          [[ARAppDelegate sharedAppDelegate].priceDict valueForKey:[dict valueForKey:@"CODE"]]];
}
Run Code Online (Sandbox Code Playgroud)

然后你可以使用outStr,就像它是一个NSString.正如汤姆在评论中指出的那样,你可以在完成时将其NSMutableString变成一个NSString,使用:

NSString *result = [NSString stringWithString:outStr];

[outStr release]; // <-- add this line and remove the autorelease
                  //     from the outStr alloc/init line
Run Code Online (Sandbox Code Playgroud)

使您的代码可重用且易于维护.