objective c - How to fix long NSString crash? -
in app i'm working on i'm reading numerical values text file in loop doing calculations , appending result results string.
the file has 22050 values in it. noticed above number of loops/values appended (~5300) tends crash.
i thought perhaps have memory leak, got rid of string appending , worked fine. tried getting rid of string appending , app crashed. have break point on exceptions , don't exception.
i wanted make sure started new project. put there 1 uibutton when pushed calls piece of code:
- (ibaction)testpressed:(id)sender { nsstring *teststring = @""; (int = 0; < 22050; i++) { teststring = [teststring stringbyappendingstring:@"12.34567890\n"]; } nslog(@"%@", teststring); }
i have break point on nslog line. app crashes before.
is there limit on nsstring length? use memory?
the problem creating new string in every iteration. there 2 options fix this: either use mutable string create result:
nsmutablestring *teststring = [nsmutablestring string]; (int = 0; < 22050; i++) { [teststring appendstring:@"12.34567890\n"]; } nslog(@"%@", teststring);
... or use autorelease pool remove instances in loop:
nsstring *teststring = @""; (int = 0; < 22050; i++) { @autoreleasepool { teststring = [teststring stringbyappendingstring:@"12.34567890\n"]; } } nslog(@"%@", teststring);
please note included second version demonstrate why problem occurred in first place , how fix it. still inefficient creates 22049 temporary strings average length of 120,000 characters.
Comments
Post a Comment