2011-10-29 95 views
27

如何將一個方法作爲參數傳遞給另一個方法?我正在跨班級做這個。Objective-C傳遞方法作爲參數

A類:

+ (void)theBigFunction:(?)func{ 
    // run the func here 
} 

B類:

- (void)littleBFunction { 
    NSLog(@"classB little function"); 
} 

// somewhere else in the class 
[ClassA theBigFunction:littleBFunction] 

C類:

- (void)littleCFunction { 
    NSLog(@"classC little function"); 
} 

// somewhere else in the class 
[ClassA theBigFunction:littleCFunction] 
+1

您通過選擇器s,這是一個類似的問題: http://stackoverflow.com/questions/519600/is-it-possible-to-pass-a-method-as-an-argument-in-objective-c – utahwithak

回答

43

你正在尋找的類型是選擇器(SEL),你會得到一個方法的這樣的選擇器:

SEL littleSelector = @selector(littleMethod); 

如果該方法的參數,則只是把:他們去的地方,像這樣:

SEL littleSelector = @selector(littleMethodWithSomething:andSomethingElse:); 

此外,方法並不是真正的功能,它們被用來與啓動時將消息發送到特定的類( +)或它的特定實例(當以 - 開頭時)。函數是C型的,並不像方法那樣有一個「目標」。

一旦你選擇,你調用這個方法對你的目標(無論是類或實例)是這樣的:

[target performSelector:someSelector]; 

的一個很好的例子是UIControladdTarget:action:forControlEvents:方法在創建時通常使用UIButton或其他一些控制對象編程。

+0

你知道嗎一旦傳入函數,我將如何調用該函數?我*懷疑* [自我func]將工作。 – Jacksonkr

+3

[target performSelector:someSelector]; –

7

目標C,使該操作相對容易。 Apple提供this documentation

要直接解決您的問題,您不是調用函數,而是調用選擇器。下面是一些示例代碼:

大功能:

+ (void)theBigFunction:(SEL)func fromObject:(id) object{ 
    [object preformSelector:func] 
} 

然後,對於B類:

- (void)littleBFunction { 
    NSLog(@"classB little function"); 
} 

// somewhere else in the class 
[ClassA theBigFunction:@selector(littleBFunction) fromObject:self] 

然後,對於C類:

- (void)littleCFunction { 
    NSLog(@"classC little function"); 
} 

// somewhere else in the class 
[ClassA theBigFunction:@selector(littleCFunction) fromObject:self] 

編輯:修正發送選擇器(刪除分號)

+0

您的選擇器與方法描述不匹配,在它們末尾不應該有':'。 –

+0

哎呀,對不起。我不是一個客觀的C編碼器(我只涉及它),並且我緊緊跟隨Apple的例子! – MJD