NSObject類的performSelectorOnMainThread和performSelectorInBackground可以實現簡單的多線程編程技術
1、- (void)performSelectorInBackground:(SEL)aSelector withObject:(id)arg
創建一個線程在子線程執行,aSelector代表了新創建的線程,arg是傳入的參數
2、- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait;
該方法的作用是在主線程中,執行制定的方法(代碼塊)。
參數:
@selector就是,要定義我們要執行的方法。
withObject:arg定義了,我們執行方法時,傳入的參數對象。類型是id。(我們可以傳入任何參數)
waitUntilDone:YES指定,當前線程是否要被阻塞,直到主線程將我們制定的代碼塊執行完。
注意:
1.當前線程爲主線程的時候,waitUntilDone:YES參數無效。
2.該方法,沒有返回值
3.該方法主要用來用主線程來修改頁面UI的狀態。
sample code:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
_label=[[UILabel alloc] initWithFrame:CGRectMake(40, 40, 60, 40)];
_label.textColor=[UIColor redColor];
_label.text=@"123";
[self.view addSubview:_label];
[self performSelectorInBackground:@selector(backWork) withObject:nil];
}
-(void)backWork
{
NSLog(@"the thread is %@",[NSThread currentThread]);
sleep(2);
[self performSelectorOnMainThread:@selector(mainWork) withObject:nil waitUntilDone:NO];
}
-(void)mainWork
{
NSLog(@"the main thread is %@",[NSThread currentThread]);
_label.text=@"456";
_label.textColor=[UIColor greenColor];
}
執行結果: 2014-08-19 11:03:59.101 testApp[1848:3107] the thread is <NSThread: 0x8c504a0>{name = (null), num = 2}
2014-08-19 11:04:01.103 testApp[1848:60b] the main thread is <NSThread: 0x8c444c0>{name = (null), num = 1}
</div>