Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix long NSString crash?

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?

like image 525
Ata01 Avatar asked Dec 06 '22 08:12

Ata01


2 Answers

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.

like image 92
Nikolai Ruhe Avatar answered Dec 31 '22 00:12

Nikolai Ruhe


Use NSMutableString to append strings otherwise too much memory is allocated.

like image 44
graver Avatar answered Dec 30 '22 22:12

graver