开发者

How do I display characters to a UILabel as I loop through them?

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

And the actual method,

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

}

Now my problem is that ONLY THE LAST character that was process开发者_JAVA百科ed 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.

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.


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

so, something like this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜