我正在尝试存储一个变量,可以是Class a Method(struct objc_class& struct objc_method)或任何Object。最初我想过将它存储在一个普通的id变量中,但我遇到了一些我似乎无法摆脱的桥接问题。有没有合适的方法来做到这一点?
-(void)setV:(id)v{
id val=v;
}
[obj setV:class_getInstanceMethod(c, NSSelectorFromString(@"foo")];
错误:
Implicit conversion of C pointer type 'Method' (aka 'struct objc_method *') to Objective-C pointer type 'id' requires a bridged cast
答案 0 :(得分:2)
使用union
:
union ClassOrMethodOrUnsafeUnretainedObject
{
Class c;
Method m;
__unsafe_unretained id o;
};
union ClassOrMethodOrUnsafeUnretainedObject temp;
temp.o = @"Test";
如果您还想存储已存储的对象类型,可以将union
与enum
内的struct
合并:
struct CombinedType {
union {
Class c;
Method m;
__unsafe_unretained id o;
} value;
enum {
kCombinedTypeClass,
kCombinedTypeMethod,
kCombinedTypeUnsafeUnretainedObject,
} type;
};
struct CombinedType temp;
temp.value.o = @"Test";
temp.type = kCombinedTypeUnsafeUnretainedObject;