這是一種方法。使用此RAExpendable類可以使用基於塊的實現動態構建委託。
比方說,你代表的是:
@protocol XDelegate
-(void) foo:(id)response;
@end
從https://github.com/evadne/RAExpendable添加RAExpendable.h,RAExpendable.m到您的項目。動態添加的委託方法:
RAExpendable *expendable = [RAExpendable new];
[expendable addMethodForSelector:@selector(foo:) types:"[email protected]:@" block:^(id x, SEL sel, id response){
NSLog(@"response is %@", response);
}];
,並設置expendable
類作爲您的委託:
someObject.delegate = expendable;
現在,如果你這樣做:
[expendable performSelector:@selector(foo:) withObject:@"OK"];
你得到的字符串response is OK
。將NSLog替換爲您認爲合適的任何成功/失敗實現。從現在起,當您撥打foo:
時,該塊將執行。
如果您想對您的用例進行修改,請注意該示例的參數爲[email protected]:@
,根據運行時的Type Encoding指南表示:void return,self,SEL,object。 self
和SEL
是每個Objective-C方法中存在的兩個隱藏參數,第三個參數是該方法的第一個非隱藏參數。塊的簽名必須與方法的簽名匹配。
多個參數的任何例子嗎?另外,當將'RAExpendable'指定爲代理時''從不兼容類型'RAExpendable * __ strong''分配'id'時,我會收到此消息。 –
atulkhatri