[selfperformSelectorOnMainThread:@selector(fetchedData:) withObject:datawaitUntilDone:YES];
會(huì)創(chuàng)建一個(gè)新的線程實(shí)行fetchedData函數(shù),并傳入?yún)?shù)data,并且會(huì)等待函數(shù)退出后再繼續(xù)執(zhí)行。
- (void)fetchedData:(NSData *)responseData {
。。。
}
在多線程操作中,有一個(gè)著名的錯(cuò)誤,叫做
“Tried to obtain the web lock from a thread other than the main thread or the web thread. This may be a result of calling to UIKit from a secondary thread”,一旦出現(xiàn)這個(gè)錯(cuò)誤,程序會(huì)立即crashed。
這是由于,apple不允許程序員在主線程以外的線程中對(duì)ui進(jìn)行操作(Bug?)
而筆者在一次http異步操作中也出現(xiàn)過這個(gè)錯(cuò)誤。當(dāng)時(shí)使用了NSOperation進(jìn)行了http異步請(qǐng)求,然后使用kvo模式注冊(cè)觀察者,當(dāng)數(shù)據(jù)下載完畢后,在主線程中接收下載完畢的通知,并在observeValueForKeyPath方法中使用[tableview reloadData]更新UI。
這樣也導(dǎo)致了上述錯(cuò)誤。
解決的方法是使用performSelectorOnMainThread進(jìn)行ui的更新:
[self performSelectorOnMainThread:@selector(refresh) withObject:nil waitUntilDone:NO];