代碼: RootViewController.h RootViewController.m ...
代碼:
RootViewController.h
#import <UIKit/UIKit.h>
@interface RootViewController : UIViewController
{
UILabel *label;
}
@end
RootViewController.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;
}
}