Chr*_*ris 3 iphone nsstring ios automatic-ref-counting
我遇到了导致崩溃的内存问题.我循环遍历一个字典数组,然后在里面循环我创建的键数组.我使用该键数组中的每个键来获取字典中该键的值.然后我通过附加值来创建一个字符串.该字符串将包含大量数据.
我也在使用ARC,所以我不能手动发布.
内存峰值发生在stringByAppendingFormat行上.
NSString *theString = [[NSString alloc] init];
for (NSMutableDictionary *aDict in collectionArray)
{
for (NSString *key in itemKeys)
{
NSString *valueString = [aDict valueForKey:key];
// Memory spikes here
theString = [theString stringByAppendingFormat:@"%@,", valueString];
}
}
Run Code Online (Sandbox Code Playgroud)
而不是NSString,你应该使用NSMutableString.试试这个:
NSMutableString *theString = [[NSMutableString alloc] init];
for (NSMutableDictionary *aDict in collectionArray)
{
for (NSString *key in itemKeys)
{
NSString *valueString = [aDict valueForKey:key];
// Memory spikes here
[theString appendFormat:@"%@,", valueString];
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:
如果您的字典和长度itemKeys不是特别大,这可能会解决您的问题.但是,如果它们很大,你需要在循环中使用autoreleasepool,就像它们在这里一样:https://stackoverflow.com/a/7804798/211292另外,如果你所做的只是将值分开,请考虑Tommy的变化逗号.
| 归档时间: |
|
| 查看次数: |
902 次 |
| 最近记录: |