【代码笔记】iOS-performSelectorOnMainThread

时间:2021-04-12 23:45:33

代码:

RootViewController.h

【代码笔记】iOS-performSelectorOnMainThread
#import <UIKit/UIKit.h>

@interface RootViewController : UIViewController
{
UILabel *label;
} @end
【代码笔记】iOS-performSelectorOnMainThread

RootViewController.m

【代码笔记】iOS-performSelectorOnMainThread
- (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;
} }
【代码笔记】iOS-performSelectorOnMainThread