gpt4 book ai didi

iOS:UITextView 未更新添加新内容

转载 作者:行者123 更新时间:2023-11-29 00:18:58 24 4
gpt4 key购买 nike

我需要以编程方式向 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 没有在 View 中更新吗?

最佳答案

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

如果你想在你的 TextView 中添加 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);
}
}
}

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

关于iOS:UITextView 未更新添加新内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44528964/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com