In an app I'm working on I'm reading numerical values from a text file in a for loop then doing some calculations and appending the result to a results string.
The file has 22050 values in it. I noticed that above a certain number of loops/values appended (~5300) it tends to crash.
I thought perhaps I have a memory leak, so I got rid of the string appending and everything worked fine. I tried getting rid of everything but the string appending and the app crashed. I have a break point on all exceptions and I don't get any exception.
I wanted to make sure so I started a new project. All I put there is one UIButton that when pushed calls this piece of code:
- (IBAction)TestPressed:(id)sender
{
NSString *testString = @"";
for (int i = 0; i < 22050; i++)
{
testString = [testString stringByAppendingString:@"12.34567890\n"];
}
NSLog(@"%@", testString);
}
I have a break point on the NSLog line. The app crashes before.
Is there a limit on NSString length? Does it use too much memory?
The problem is that you are creating a new string in every iteration. There are two options to fix this: Either use a mutable string to create the result:
NSMutableString *testString = [NSMutableString string];
for (int i = 0; i < 22050; i++)
{
[testString appendString:@"12.34567890\n"];
}
NSLog(@"%@", testString);
... or use an autorelease pool to remove the instances in the loop:
NSString *testString = @"";
for (int i = 0; i < 22050; i++)
{
@autoreleasepool {
testString = [testString stringByAppendingString:@"12.34567890\n"];
}
}
NSLog(@"%@", testString);
Please note that I included the second version only to demonstrate why the problem occurred in the first place and how to fix it. It is still inefficient as it creates 22049 temporary strings with an average length of 120,000 characters.
Use NSMutableString
to append strings otherwise too much memory is allocated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With