user2924482 user2924482 -4 years ago 102
Objective-C Question

iOS: UITextView not updating adding new content

I need to be adding text programmatically to UITextView but the UITextView is not updating in the main view. Here is my code:

- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:YES];
self.textView.text = @"This is the beginning";
[self addingText];
}

-(void)addingText
{
for (int i = 0; i < 10000; i++) {
NSString *str = [NSString stringWithFormat: @"%@%@", _textView.text,@"\n"];
NSString *line = [NSString stringWithFormat:@"line number : %d",i];
str = [str stringByAppendingString:line];
self.textView.text = str;

}
}


If I do po _textView.text I can see all the content add it to UITextView.

Any of you know what is going or why the UITextView is not updating in the view?

I'll really appreciate your help.

Answer Source

Are you simply trying to crash your app?

If you want to add 10,000 lines to your text view, try it like this:

-(void)addingText
{
    // get the current content of the text view, and add "\n" to it (one time only)
    NSString *str = [NSString stringWithFormat: @"%@%@", _textView.text, @"\n"];

    for (int i = 0; i < 10000; i++) {
        // create a new local variable with "Line number ##" counter
        NSString *line = [NSString stringWithFormat:@"line number : %d\n",i];
        // append the new variable to the existing str variable
        str = [str stringByAppendingString:line];
    }

    // set the .text of the text view to the content of the str variable (one time only)
    self.textView.text = str;

}

Edit: To add a little explanation...

Your original code, with comments:

-(void)addingText // Bad method
{
    for (int i = 0; i < 10000; i++) {
        // copy the .text from the text view into a new local variable and append "\n" to it
        NSString *str = [NSString stringWithFormat: @"%@%@", _textView.text,@"\n"];
        // create a new local variable with "Line number ##" counter
        NSString *line = [NSString stringWithFormat:@"Line number : %d",i];
        // append the new variable to the other local variable
        str = [str stringByAppendingString:line];
        // set the .text of the text view to the content of the local str variable
        self.textView.text = str;
        if (i % 100 == 0) {
            NSLog(@"at %d", i);
        }
    }
}

As you see, every time through the loop you are making a copy of the text in the text view, then you append to it, then you insert it back into the text view. If you run this code you will see the console debug log every 100th time through the loop... and you will see how very, very slow it is. If you change the number from 10000 to 100, you will see that your text view updates, but it takes a second or so. To run the 10000 times may take several minutes (if it doesn't crash due to memory use - I never let it run all the way).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download