如何从iOS中的非UI线程更新UI标签
我是新的iOS开发,我有普通的目标-c类“MoneyTimer.m”运行计时器,从那里我想更新一个用户界面的标签与更改的计时器的值。 我想知道如何从非UI线程访问UI元素? 我使用Xcode 4.2和故事板。
在黑莓简单地通过获取事件locking,可以从非UI线程更新UI。
//this the code from MyTimerClass {... if(nsTimerUp == nil){ nsTimerUp = [NSTimer scheduledTimerWithTimeInterval: 1.0 target:self selector:@selector(countUpH) userInfo:nil repeats: YES]; ...} (void) countUpH { sumUp = sumUp + rateInSecH; **//from here i want to update the UI label ** ... }
这是最快最简单的方法是:
- (void) countUpH{ sumUp = sumUp + rateInSecH; //Accessing UI Thread [[NSOperationQueue mainQueue] addOperationWithBlock:^{ //Do any updates to your label here yourLabel.text = newText; }]; }
如果你这样做,你不必切换到不同的方法。
希望这可以帮助。
山姆
你的问题没有给出太多的信息或细节,所以很难确切地知道你需要做什么(例如,如果有任何“线程”问题等)。
无论如何,假设你的MoneyTimer实例有一个对当前viewController的引用,你可以使用performSelectorOnMainThread
。
//
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait;
我过去做了一些相同的事情。
我用一个函数来设置标签文本:
- (void)updateLabelText:(NSString *)newText { yourLabel.text = newText; }
然后用performSelectorOnMainThread在主线程上调用这个函数
NSString* myText = @"new value"; [self performSelectorOnMainThread:(@selector)updateLabelText withObject:myText waitUntilDone:NO];
正确的方法是这样的:
- (void) countUpH { sumUp = sumUp + rateInSecH; //Accessing UI Thread dispatch_async(dispatch_get_main_queue(), ^{ //Do any updates to your label here yourLabel.text = newText; }); }
假设标签生活在同一个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"; }