简体   繁体   中英

How to change a UILabel property when NSNotification occurs

I'm looking everywhere on Internet and on my books but i can't find a solution to a problem which seems very stupid!

I've an application with a background thread which checks whether the iPhone is connected or not.When the connection state changes the thread fires an NSNotification on notification center and the mainviewcontroller listens on it. When the event occurs , the mainviewcontroller selector registered on the notification center is called and for console operations works perfectly.

Here becomes the problem, if i would change label or do some interactions with the view , all the calls to uiview elements are ignored.I've tried with uiview animation blocks to change alpha or call setNeedsDisplay but there is no way to interact with the view.

How can I do this?

NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];

[nc addObserver:self 
    selector:@selector(changedOnlineStatus:) 
    name:@"onlineStatus" 
    object:nil];

-(void)changedOnlineStatus:(NSNotification*)notification
{
    NSDictionary* note = (NSDictionary*)[notification userInfo];

    NSString* onlineStat = (NSString*)[note objectForKey:@"isOnline"];
    if([onlineStat isEqualToString:@"YES"])
    {
        offlineLabel.alpha=1;
    }
    else
    {
        offlineLabel.alpha=1;
    }
}

Sounds to me like the problem is the thread. You should only update UI elements from the main thread and not a background thread. Try dispatching the call to the main thread:

dispatch_async(dispatch_get_main_queue(), ^{

    offlineLabel.alpha=1;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM