Problem with a thread and changing the image for a UIImageView

Discussion in 'iOS Programming' started by ulbador, Dec 2, 2010.

  1. ulbador macrumors 68000

    ulbador

    Joined:
    Feb 11, 2010
    #1
    I'm having a completely confusing issue with trying to change an image. I assume it is somehow related to using a thread and an auto release pool.

    Basically:


    Code:
    - (void)connectionThread:(id) sender {
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
        while (YES){
            connectedIv.image = nil;
            if (connected) {
                connectedIv.image = [UIImage imageNamed:@"connected.png"];
                NSLog(@"Connected");
            } else {
                connectedIv.image = [UIImage imageNamed:@"notconnected.png"];
            }
            [NSThread sleepForTimeInterval:5.0];
        }
    
        [pool release];
    }
    
    
    I've taken all other code out and just put the relevant stuff, and for simplicity, just made the thread forever running. Basically this method is a thread that is detached. The method runs fine and as expected, except the image never changes.

    "connected" is a bool set outside of the method, and "connectedIv" is a UIImageView connected via Interface Builder via all the normal methods.

    The first time around the loop, before the "connected" bool has been set to YES, the correct image displays. After that, the NSLog prints out, but the image doesn't change. I swear I've messed around with something like this before and it worked, the major difference being the auto release pool and the thread.

    Thanks!
     
  2. dejo Moderator

    dejo

    Staff Member

    Joined:
    Sep 2, 2004
    Location:
    The Centennial State
    #2
    All UI changes must be performed on the main thread.
     
  3. ulbador thread starter macrumors 68000

    ulbador

    Joined:
    Feb 11, 2010
    #3
    Wow.. Thanks! A simple:

    [self performSelectorOnMainThread:mad:selector(updateConnectedImage) withObject:nil waitUntilDone:NO];

    and I'm fixed! :)
     

Share This Page