2012-11-28 103 views
11

在下面的摘錄背景,調用類方法中使用目標C

/*A ClassName with instanceMethod and ClassMethod */ 

-(void)instanceMethod; 

+(void)ClassMethod; 

/*To call a instance method in background */ 

ClassName class1obj = [ClassName alloc] init]; 

[class1obj performSelectorInBackground:@selector(instanceMethod) withObject:nil]; 

同樣,如何使用performSelectorInBackground調用類方法的背景嗎?

如果可能,請解釋! 請人攜手..

回答

18

只需撥打

[ClassName performSelectorInBackground:@selector(ClassMethod) withObject:nil]; 

因爲類是對象本身,這將工作。

+1

薰得像魅力! – itechnician

2

請嘗試self,而不是類名

[self performSelectorInBackground:@selector(methodTobeCalled) withObject:nil]; 

希望這個WIL工作,你

1

你應該看看GCD(大中央調度),解決了一般的問題「如何在執行代碼的背景」。無論是調用類方法,調用實例方法,拋擲骰子,寫入文件,無論如何。

實施例:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
    NSLog (@"This is code running in the background"); 
    [MyClass someClassMethod]; 
    [myInstance someMethodWithInt:1 bool:YES string:@"some string"]; 
    NSLog (@"Finished with the background code"); 
}); 

與任意代碼作品;不需要使用選擇器,也不需要編寫方法只是讓選擇器在後臺運行,不需要將參數轉換爲NSObject(不能使用帶有int或BOOL參數的performSelector)。 Xcode會自動爲您填寫大部分內容。