iOS: UITextView 未更新添加新内容

iOS: UITextView not updating adding new content

我需要以编程方式向 UITextView 添加文本,但 UITextView 未在主视图中更新。
这是我的代码:

    - (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;

        }
    }

如果我这样做 po _textView.text 我可以看到所有内容将其添加到 UITextView

你们中有人知道发生了什么或为什么 UITextView 没有在视图中更新吗?

您只是试图让您的应用程序崩溃吗?

如果你想在你的文本视图中添加 10,000 行,试试这样:

-(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;

}

编辑: 添加一点解释...

您的原始代码,带有注释:

-(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);
        }
    }
}

如您所见,每次通过循环,您都在复制文本视图中的文本,然后附加到它,然后将它插入回文本视图。如果你 运行 这段代码,你将在循环中每第 100 次看到控制台调试日志......你会发现它是多么非常非常慢。如果将数字从 10000 更改为 100,您 看到文本视图更新,但这需要一秒钟左右的时间。到 运行 10000 次可能需要几分钟(如果它没有因为内存使用而崩溃 - 我从来没有让它一直 运行)。