就我而言,這與其他的「我可以檢查塊的類型」帖子有什麼不同?Objective-C類型檢查塊?
我想知道,如果給定未知簽名的塊對象,我可以在調用之前瞭解它接受哪些參數?
我有一種情況,我有一些與字典中的對象相關的回調。我希望這些回調中的一些能夠期待一組不同的參數。這裏的例子是非常簡單的,但我認爲它得到了重點。
如何判斷一個塊是否是我之前鍵入的類型?
//MyClass.m
// I start by declare two block types
typedef void (^callbackWithOneParam)(NSString*);
typedef void (^callbackWithTwoParams)(NSString*, NSObject*);
........
// I create a dictionary mapping objects to callback blocks
self.dict = @{
@"name": "Foo",
@"callback": ^(NSString *aString) {
// do stuff with string
}
}, {
@"name": "Bar",
@"callback": ^(NSString *aString, NSObject *anObject) {
// do stuff with string AND object
}
}
.....
// Later, this method is called.
// It looks up the "name" parameter in our dictionary,
// and invokes the associated callback accordingly.
-(void) invokeCallbackForName:(NSString*)name {
// What is the type of the result of this expression?
[self.dict objectForKey: name]
// I want to say: (pseudocode)
thecallback = [self.dict objectForKey: name];
if (thecallback is of type "callbackWithOneParam") {
thecallback(@"some param")
}
else if (thecallback is of type "callbackWithTwoParams") {
thecallback(@"some param", [[NSObject alloc] init]);
}
}
我覺得你不能。在你的情況下,你可以留下額外的參數NSObject,如果你不使用它,則放入nil。 – SAKrisT
在這個例子中,對字典中的所有塊使用一致的簽名更加可取。每個塊內的代碼可以獨立決定哪些參數將被使用或忽略。在調用塊之前,還必須將'-objectForKey:'的返回值轉換爲塊簽名。在將其添加到字典之前,您還必須將每個塊複製到堆中。 – Darren
Darren能否詳細說明你的最後兩條語句,謝謝! –