2011-06-12 97 views
1

我有一个环,看起来像这样目标C - 环更改标签文本

for(int x=0; x < 10; x++){ 
    [testLabel setText:[self randomString]]; 
    sleep(1); 
} 

的randomString是它返回来自阵列的随机串的方法。

我使用睡眠,所以它实际上可以看到正在更改的标签。

循环工作正常,但标签仅在循环的最后一次迭代后才会更新。

有谁知道这可能是为什么?有没有办法解决它?

+0

[NSTextField可能重复等待,直到更新循环结束](http://stackoverflow.com/questions/5829977/nstextfield-waits-until-the-end-of-a-loop-to-update ) – 2011-06-12 22:50:37

+1

此外:[调用睡眠(5)和更新文本字段不工作](http://stackoverflow.com/questions/5834062/calling-sleep5-and-updating-text-field-not-working) – 2011-06-12 22:51:05

回答

3

UI仅在运行循环结束时更新,其循环运行在单次迭代中。您应该使用NSTimer代替。

0

及最新您需要单独运行它:

for(int x=0; x < 10; x++){ 
    [self performSelectorOnMainThread:@selector(updateLabel) withObject:nil waitUntilDone:NO]; 
    sleep(1); 
} 

- (void) updateLabel { 
    [testLabel setText:[self randomString]]; 
} 
+1

没有必要一个线程......浪费资源。 – bbum 2011-06-12 23:05:08

+0

假设循环在主线程上运行,这会产生同样的问题,因为'sleep()'调用会阻止回调做任何事情,直到为时已晚。 – 2011-06-12 23:34:14

4

不要调用sleep()

当然不是有史以来主线程和辅助线程任何使用sleep上通常是非常值得怀疑的。

在这种情况下,只需使用NSTimer实例来定期更新该值(如Wilbur所述)。

0

这是更好,如果你在后台线程

[self performSelectorInBackground:@selector(updateBusyLabel:) withObject:[NSString stringWithFormat:@"Processing ... %i",iteration]]; 

-(void)updateBusyLabel:(NSString *)busyText { 
    [_busyLabel setText:busyText]; 
} 

我不会使用睡眠()运行你的字符串,并且定时器的工作太多了。