如何強制編譯器從一組共享相同名稱的類方法中選擇所需的方法?兩個類方法,相同名稱,不同簽名:如何強制編譯器使用預期的方法?
/* Use +[MyClass port](UInt16 (*)(id, SEL),
* not +[NSPort port](NSPort *(*)(id, SEL)). */
UInt16 port = [[self class] port];
我有一個Objective-C類與類方法:
+ (UInt16)port;
NSPort
有一個便利的構造函數的簽名衝突與此:
+ (NSPort *)port;
發送+port
我的課結果在編譯器中警告:
UInt16 port = [[self class] port];
W: Multiple methods named '+port' found
W: Using '+(NSPort *)port'
W: Also found '+(UInt16)port'
失敗:編譯器選擇了錯誤的方法簽名。
類型推斷失敗:使用[[(MyClass *)self class] port]
不會使用正確的方法將其拼合到一起。
ETA:這裏是我用現在的解決方法:
#import <objc/runtime.h>
Class c = [self class];
SEL s = @selector(port);
typedef UInt16 (*PortIMP)(id, SEL);
PortIMP MyClassGetPort = (PortIMP)class_getMethodImplementation(c, s);
UInt16 port = MyClassGetPort(c, s);
正是在這種良好:
- 它處理正確地分配給任一子類實現。
- 它僅限於實現文件,所以這個醜陋不會造成任何人,除了實施者。
這是壞的,它不會幫助任何其他人想要調用該方法。
MyClass&NSPort之間有什麼關係? – kikito 2011-04-11 16:15:15
@egarcia:沒有關係。 'NSPort'頭由Foundation框架導入。 – 2011-04-11 16:21:06