代码:
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; } }