Objective c 在ObjC中的变量内存储类、方法或对象
我试图在变量中存储一些可以是类a方法(struct objc_Class&struct objc_Method)或任何对象的内容。起初我想把它存储在一个普通的id变量中,但我遇到了一些桥接问题,这些问题似乎无法解决。有没有合适的方法可以做到这一点Objective c 在ObjC中的变量内存储类、方法或对象,objective-c,generics,objective-c-runtime,Objective C,Generics,Objective C Runtime,我试图在变量中存储一些可以是类a方法(struct objc_Class&struct objc_Method)或任何对象的内容。起初我想把它存储在一个普通的id变量中,但我遇到了一些桥接问题,这些问题似乎无法解决。有没有合适的方法可以做到这一点 -(void)setV:(id)v{ id val=v; } [obj setV:class_getInstanceMethod(c, NSSelectorFromString(@"foo")]; 错误: Implicit conversion
-(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 ClassOrMethodOrUnsafeUnretainedObject
{
Class c;
Method m;
__unsafe_unretained id o;
};
union ClassOrMethodOrUnsafeUnretainedObject temp;
temp.o = @"Test";
如果还想存储存储的对象类型,可以将联合
与枚举
组合在结构
中:
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;
对于您所说的这些桥接问题,您认为在显示代码的同时显示编译器投诉是一个好主意吗?“as Method(structs)”是什么意思?显然,此用户喜欢对问题保持神秘的气氛。@zaph的问题和谜团有很强的关联:)有谜团和没有答案的问题有很强的关联。@Trojafoe我已将你的建议添加到我的答案中。在大多数情况下,还记得你存储了哪种价值是很好的。太棒了!非常感谢:)