不是本人原創,只是在學習過程中遇到的問題,對其進行摘錄!
-(BOOL) isKindOfClass: classObj 用來判斷是否是某個類或其子類的執行個體
-(BOOL) isMemberOfClass: classObj 用來判斷是否是某個類的執行個體
-(BOOL) respondsToSelector: selector 用來判斷是否有以某個名字命名的方法(被封裝在一個selector的對象裡傳遞)
+(BOOL) instancesRespondToSelector: selector 用來判斷執行個體是否有以某個名字命名的方法. 和上面一個不同之處在於, 前面這個方法可以用在執行個體和類上,而此方法只能用在類上.
-(id) performSelector: selector
SEL sel = @selector (start:) ; // 指定action
if ([obj respondsToSelector:sel])
{ //判斷該對象是否有相應的方法
[obj performSelector:sel withObject:self]; //調用選取器方法
}
使用[[UIApplication sharedApplication] keyWindow]尋找應用程式的主視窗對象
[selfperformSelectorOnMainThread:@selector(fetchedData:) withObject:datawaitUntilDone:YES];
會建立一個新的線程實行fetchedData函數,並傳入參數data,並且會等待函數退出後再繼續執行。
- (void)fetchedData:(NSData *)responseData {
。。。
}
用到的類是NSThread類,這裡使用detachNewTheadSelector:toTagaet:withObject建立一個線程。
函數setupThread:(NSArray*)userInfor。通過userInfor將需要的資料傳到線程中。
函數定義:
-(void)setupThread:(NSArray*)userInfor{
[NSThread detachNewThreadSelector:@selector(threadFunc:) toTarget:self withObject:(id)userInfor];
}
- (void)threadFunc:(id)userInfor{
NSAutoreleasePool*pool = [[NSAutoreleasePool alloc] init];
//。。。。需要做的處理。
//這裡線程結束後立即返回
[self performSelectorOnMainThread:@selector(endThread) withObject:nil waitUntilDone:NO];
[pool release];
}
performSelectorOnMainThread通知主線程執行函數endThread。也可以使用performSelector:onThread:withObject:waitUntil 通知某線程執行線程結束後的處理
在多線程操作中,有一個著名的錯誤,叫做“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”,一旦出現這個錯誤,程式會立即crashed。
這是由於,apple不允許程式員在主線程以外的線程中對ui進行操作(Bug?)
而筆者在一次http非同步作業中也出現過這個錯誤。當時使用了NSOperation進行了http非同步請求,然後使用kvo模式註冊觀察者,當資料下載完畢後,在主線程中接收下載完畢的通知,並在observeValueForKeyPath方法中使用[tableview reloadData]更新UI。
這樣也導致了上述錯誤。
解決的方法是使用performSelectorOnMainThread進行ui的更新:
[self performSelectorOnMainThread:@selector(refresh) withObject:nil waitUntilDone:NO];