Reputation: 55
I want to update a label on an iPhone form from a separate thread. The thread is running but the label is not updated.
here is my code
-(void)launchThread:(id)param;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
...
-(void) launchThread:(id)param{
UILabel *control = (UILabel*)param;
NSMutableString *str;
for (int i=0; i<1000; i++) {
str = [NSMutableString stringWithFormat:@"%d",i];
control.text=str;
NSLog(@"%@",str);
sleep(1);
}}
...
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[NSThread detachNewThreadSelector:@selector(launchThread:) toTarget:self withObject:timeLabel];
}
I guess the label's text is updated but not refreshed on the form. How do I refresh it?
I have tried to look for similar posts but they did not work for me. Sorry if I repeated the question.
Upvotes: 2
Views: 1073
Reputation: 8570
In iOS you can only use the main thread to update the interface.
There are two things you can do to update the interface from a thread very easily. Using a method of NSObject like so:
[self performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait];
And using blocks and GCD:
dispatch_async(dispatch_get_main_queue(),{
//code to execute on main thread
});
Upvotes: 1
Reputation: 4254
@jackslash is correct, you can only update the interface on the main thread (UI thread). I would suggest using performSelectorOnMainThread
to update your UILabel. I think the syntax is something like:
[self.label performSelectorOnMainThread : @ selector(setText : ) withObject:str waitUntilDone:YES];
Not quite certain tho. Do some googling and you should be able to find a working example with it.
Upvotes: 2