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

时间:2011-03-28 15:16:45

标签: 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"]]];

}

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

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]]; 

//这到达方法的结尾

1 个答案:

答案 0 :(得分: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"]]];
}

然后您可以使用outStr,就好像它是NSString一样。正如Tom在评论中指出的那样,您可以在完成后将NSMutableString变为NSString,使用:

NSString *result = [NSString stringWithString:outStr];

[outStr release]; // <-- add this line and remove the autorelease
                  //     from the outStr alloc/init line

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