IPhone: huge spike in memory when creating NSString in a loop

I have a memory issue that is causing it to crash. I loop through an array of dictionaries and then internally that I go through the array of keys I created. I am using each key in this array of keys to get the value of that key in the dictionary. Then I create a string by adding values. This line will contain a large amount of data.

I am also using ARC so I cannot manually release.

The memory spike occurs in 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];
    }
}

      

+3


source to share


2 answers


Instead, NSString

you should use NSMutableString

. Try the following:

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

      



Edit: This will probably solve your problems if your vocabulary and lengths are itemKeys

not very large. However, if they are large, you need to use autoreleasepool in your loop as they do: fooobar.com/questions/764005 / ... Also, consider changing Tommy if all you are doing is separating the values ​​with commas.

+7


source


By postponing answers to questions elsewhere, you are constantly creating a new line that includes the old plus the extra, leaving the old in the autodefinition pool, which won't merge at least until you exit the method: / p>

NSArray *values = [aDict objectsForKeys:itemKeys notFoundMarker:@""];
theString = [values componentsJoinedByString:@","];

      



It would seem to do what you want (well, if you add an extra comma to the end) without explicitly sorting out the inner loop.

+4


source







All Articles