遍历字符时如何在UILabel中显示字符? [英] How do I display characters to a UILabel as I loop through them?

查看:58
本文介绍了遍历字符时如何在UILabel中显示字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在单独的线程上执行循环的方法。出于对我的程序有效的原因,我使用以下方法调用此方法,

I have a method that performs a loop on a separate thread. For reasons that work for my program I call this method using,

[self performSelectorInBackground:@selector(myMethod:) withObject:arg];

以及实际方法,

- (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];

}

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

Now my problem is that ONLY THE LAST character that was processed gets displayed in my UILabel, yet when I check my console while running the program, as the characters are being processed they are being displayed to the console one-by-one (using NSLog). This is exactly the behavior I'd like to see going on in my label.

另外,我应该告诉您,每次处理字符时(在开关中语句)至少有一点延迟,因为我至少要调用 [NSThread sleepForTimeInterval:delayTime];

Also I should tell you that every time I'm processing a characters (in the switch statement) there is a least a slight delay because i'm calling [NSThread sleepForTimeInterval:delayTime]; at least a couple times.

推荐答案

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

You are attempting to update a view (your "outputLabel") from a thread other than the main thread, and this is not allowed.

您需要强制从主线程进行更新。您可以通过调用

You need to force the update to happen from the main thread. You can do this by calling

- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait

所以,像这样:

[viewController.outputLabel performSelectorOnMainThread: @selector( setText: ) withObject: currentChar waitUntilDone: YES];

这篇关于遍历字符时如何在UILabel中显示字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆