当我循环播放UILabel时,如何向UILabel显示字符?

cgo*_*ain 0 iphone cocoa-touch ios

我有一个方法在一个单独的线程上执行循环.由于适用于我的程序的原因,我将此方法称为,

[self performSelectorInBackground:@selector(myMethod:) withObject:arg];
Run Code Online (Sandbox Code Playgroud)

而实际的方法,

- (void)myMethod:(NSString *)arg {
    NSAutoreleasePool *pool = [NSAutoreleasePool new];
    for (int i = 0; i < [arg length]; i++) {

    unichar ch = [arg characterAtIndex:i];
    NSLog(@"Processing character %c",ch);

    NSString *currentChar = [[NSString alloc] initWithFormat:@"%c", ch];
    viewController.outputLabel.text = currentChar;
    [currentChar release];


    switch (ch) {
    //Do my stuff
    }

    [pool release];

}
Run Code Online (Sandbox Code Playgroud)

现在我的问题是,只有处理过的最后一个字符会显示在我的UILabel中,但是当我在运行程序时检查我的控制台时,正在处理字符时,它们会逐个显示到控制台(使用NSLog) ).这正是我希望在我的标签中看到的行为.

另外我应该告诉你,每次我处理一个字符(在switch语句中)都会有一点延迟,因为我[NSThread sleepForTimeInterval:delayTime];至少要调用几次.

Tom*_*ift 5

您正在尝试从主线程以外的线程更新视图(您的"outputLabel"),这是不允许的.

您需要从主线程强制更新.你可以通过电话来做到这一点

- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait
Run Code Online (Sandbox Code Playgroud)

所以,像这样:

[viewController.outputLabel performSelectorOnMainThread: @selector( setText: ) withObject: currentChar waitUntilDone: YES];
Run Code Online (Sandbox Code Playgroud)