在 ObjC 中存储 Class、方法或对象内部变量

Storing a Class, Method or Object inside variable in ObjC

我试图在变量中存储一些东西,它可以是 Class 方法(结构 objc_class 和结构 objc_method)或任何对象。最初我想只是将它存储在一个普通的 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

使用 union:

union ClassOrMethodOrUnsafeUnretainedObject
{
    Class c;
    Method m;
    __unsafe_unretained id o;
};

union ClassOrMethodOrUnsafeUnretainedObject temp;
temp.o = @"Test";

如果你还想存储你存储的对象类型,你可以将unionenum组合在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;