首页 > 代码库 > performSelectorOnMainThread

performSelectorOnMainThread

 

 

[self performSelectorOnMainThread:@selector(loadData) withObject:nil waitUntilDone:NO];

 

 

 performSelectorOnMainThread的作用就如其名,是在主线程执行某个selector, 所有的UIKit里的调用必须是在主线程的,在非主线程调用会产生非预期的结果也很可能会造成crash,所以当你在其他线程想执行一段UI调用的代码时,就需要用到这个方法了

 

代码.

 

.h部分

 

#import <UIKit/UIKit.h>@interface RootViewController : UIViewController{    UILabel *label;}@end

 

.m部分

 

- (void)viewDidLoad{    [super viewDidLoad];    // Do any additional setup after loading the view.        self.title=@"performSelectorOnMainThread";    }-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{    // performSelectorOnMainThread的作用就如其名,是在主线程执行某个selector, 所有的UIKit里的调用必须是在主线程的,在非主线程调用会产生非预期的结果也很可能会造成crash,所以当你在其他线程想执行一段UI调用的代码时,就需要用到这个方法了        [self performSelectorOnMainThread:@selector(loadData) withObject:nil waitUntilDone:NO];    }-(void)loadData{    if (!label) {        label=[[UILabel alloc]init];        label.frame=CGRectMake(50, 80, 200, 200);        label.backgroundColor=[UIColor redColor];        [self.view addSubview:label];    }else    {        [label removeFromSuperview];        label=nil;    }    }