我有一个环,看起来像这样目标C - 环更改标签文本
for(int x=0; x < 10; x++){
[testLabel setText:[self randomString]];
sleep(1);
}
的randomString是它返回来自阵列的随机串的方法。
我使用睡眠,所以它实际上可以看到正在更改的标签。
循环工作正常,但标签仅在循环的最后一次迭代后才会更新。
有谁知道这可能是为什么?有没有办法解决它?
我有一个环,看起来像这样目标C - 环更改标签文本
for(int x=0; x < 10; x++){
[testLabel setText:[self randomString]];
sleep(1);
}
的randomString是它返回来自阵列的随机串的方法。
我使用睡眠,所以它实际上可以看到正在更改的标签。
循环工作正常,但标签仅在循环的最后一次迭代后才会更新。
有谁知道这可能是为什么?有没有办法解决它?
UI仅在运行循环结束时更新,其循环运行在单次迭代中。您应该使用NSTimer
代替。
及最新您需要单独运行它:
for(int x=0; x < 10; x++){
[self performSelectorOnMainThread:@selector(updateLabel) withObject:nil waitUntilDone:NO];
sleep(1);
}
- (void) updateLabel {
[testLabel setText:[self randomString]];
}
没有必要一个线程......浪费资源。 – bbum 2011-06-12 23:05:08
假设循环在主线程上运行,这会产生同样的问题,因为'sleep()'调用会阻止回调做任何事情,直到为时已晚。 – 2011-06-12 23:34:14
这是更好,如果你在后台线程
[self performSelectorInBackground:@selector(updateBusyLabel:) withObject:[NSString stringWithFormat:@"Processing ... %i",iteration]];
-(void)updateBusyLabel:(NSString *)busyText {
[_busyLabel setText:busyText];
}
我不会使用睡眠()运行你的字符串,并且定时器的工作太多了。
[NSTextField可能重复等待,直到更新循环结束](http://stackoverflow.com/questions/5829977/nstextfield-waits-until-the-end-of-a-loop-to-update ) – 2011-06-12 22:50:37
此外:[调用睡眠(5)和更新文本字段不工作](http://stackoverflow.com/questions/5834062/calling-sleep5-and-updating-text-field-not-working) – 2011-06-12 22:51:05