How to update a UI label from a non UI thread in iOS

前端 未结 5 1429
情深已故
情深已故 2021-02-05 07:17

I am new to iOS development, I have plain objective -c class \"MoneyTimer.m\" for running timer, from there i want to update the an UI label with the changing value of timer.

相关标签:
5条回答
  • 2021-02-05 07:42

    Your question doesn't give much info or detail so it is hard to know exactly what you need to do (e.g. if there is a "thread" issue at all, etc.).

    At any rate, assuming your MoneyTimer instance has a reference to the current viewController you can use performSelectorOnMainThread.

    //

    - (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait;
    
    0 讨论(0)
  • 2021-02-05 07:47

    I've done something identical in the past.

    I used a function to set the label text:

    - (void)updateLabelText:(NSString *)newText {
        yourLabel.text = newText;
    }
    

    and then called this function on the main thread with performSelectorOnMainThread

    NSString* myText = @"new value";
    [self performSelectorOnMainThread:(@selector)updateLabelText withObject:myText waitUntilDone:NO];
    
    0 讨论(0)
  • 2021-02-05 07:54

    This is the quickest and simplest way to do it is:

    - (void) countUpH{
    
       sumUp = sumUp + rateInSecH;
       //Accessing UI Thread
       [[NSOperationQueue mainQueue] addOperationWithBlock:^{
    
          //Do any updates to your label here
          yourLabel.text = newText;
    
       }];
    }
    

    If you do it this way you don't have to switch to a different method.

    Hope this helps.

    Sam

    0 讨论(0)
  • 2021-02-05 08:01

    The proper way is this:

    - (void) countUpH  {
       sumUp = sumUp + rateInSecH;
       //Accessing UI Thread
       dispatch_async(dispatch_get_main_queue(), ^{
    
       //Do any updates to your label here
        yourLabel.text = newText;
       });
    }
    
    0 讨论(0)
  • 2021-02-05 08:04

    Assuming that label lives in the same class:

        if(nsTimerUp == nil){
            nsTimerUp = [NSTimer scheduledTimerWithTimeInterval: 1.0 target:self selector:@selector(countUpH) userInfo:nil repeats: YES];
        [self performSelectorOnMainThread:@selector(updateLabel)
                                               withObject:nil
                                            waitUntilDone:NO];
    
        }
    
    -(void)updateLabel {
        self.myLabel.text = @"someValue";
    }
    
    0 讨论(0)
提交回复
热议问题