我需要以编程方式将文字添加到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
没有更新的内容或原因吗?
答案 0 :(得分:1)
您只是尝试让您的应用崩溃吗?
如果要在文本视图中添加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次可能需要几分钟(如果由于内存使用而没有崩溃 - 我从不让它一直运行。)