ARC中的object_getInstanceVariable/object_setInstanceVariable [英] object_getInstanceVariable/object_setInstanceVariable in ARC
问题描述
为什么Objective-C运行时方法object_getInstanceVariable
和object_setInstanceVariable
在自动引用计数下不可用,我该怎么办?
Why are the Objective-C runtime methods object_getInstanceVariable
and object_setInstanceVariable
are not available under Automatic Reference Counting and what can I do about it?
object_getInstanceVariable
有问题.我该如何解决?
object_getInstanceVariable
is buggy when the instance variable's size is larger than the development target's pointer size. How can I get around this?
推荐答案
请改用valueForKey:
和setValue:forKey:
方法.这些允许您读取/写入对象的任何实例变量.对于原始类型的实例变量,这些方法返回/获取包装为NSNumber
或NSValue
对象的值.
Use the valueForKey:
and setValue:forKey:
methods instead. These allow you to read/write any instance variable of an object. For primitive-typed instance variables these methods return/take values wrapped as NSNumber
or NSValue
objects.
您拥有的实例变量大于指针大小,也许是struct
的大小?这是一些显示与struct
一起使用的代码片段,首先让我们定义一个struct
:
You have instance variables larger than the pointer size, maybe struct
's? Here are some code fragments showing use with a struct
, first let's define a struct
:
typedef struct
{
int i;
float f;
char c;
} ThreePrimitives;
和带有(私有)实例变量的类:
and a class with a (private) instance variable:
@interface StructClass : NSObject
...
@end
@implementation StructClass
{
ThreePrimitives myStruct;
}
...
@end
设置实例变量:
ThreePrimitives a = { 42, 3.14, 'x' };
NSValue *wrapA = [NSValue value:&a withObjCType:@encode(ThreePrimitives)];
[sc setValue:wrapA forKey:@"myStruct"];
要读取实例变量,请执行以下操作:
To read the instance variable:
ThreePrimitives b;
NSValue *extracted = [sc valueForKey:@"myStruct"];
[extracted getValue:&b];
HTH
这篇关于ARC中的object_getInstanceVariable/object_setInstanceVariable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!