如何强制编译器从一组共享相同名称的类方法中选择所需的方法?
/* Use +[MyClass port](UInt16 (*)(id, SEL),
* not +[NSPort port](NSPort *(*)(id, SEL)). */
UInt16 port = [[self class] port];
Run Code Online (Sandbox Code Playgroud)
我有一个带有类方法的Objective-C类:
+ (UInt16)port;
Run Code Online (Sandbox Code Playgroud)
NSPort
有一个方便构造函数,其签名与此冲突:
+ (NSPort *)port;
Run Code Online (Sandbox Code Playgroud)
发送+port
给我的类导致编译器警告:
UInt16 port = [[self class] port];
W: Multiple methods named '+port' found
W: Using '+(NSPort *)port'
W: Also found '+(UInt16)port'
Run Code Online (Sandbox Code Playgroud)
失败:编译器选择了错误的方法签名.
类型推断失败:使用[[(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);
Run Code Online (Sandbox Code Playgroud)
这很好:
这是不好的,它不会帮助任何想要调用该方法的人.
为什么不直接重命名该方法呢?(蹩脚的,我知道)你可能会说一个名为“port”的方法应该返回一个端口对象(这就是它的作用NSPort
),并且如果你想返回一个原始的“端口号”,你可以将其称为“portValue” ”(如“intValue”、“longLongValue”等)。
归档时间: |
|
查看次数: |
2019 次 |
最近记录: |