当 object_getIvar(self, myIntVar) 返回指针时,如何从 object_getIvar(self, myIntVar) 获取 int 值
如果 object_getIvar 中的变量是基本数据类型(例如 float、int、bool),根据文档,当函数返回指针(id)时,如何获取值。 我尝试过转换为 int, int* 但当我尝试将其传递给 NSLog 时,我收到有关不兼容指针类型的错误。
if the variable in object_getIvar is a basic data type (eg. float, int, bool) how do I get the value as the function returns a pointer (id) according to the documentation. I've tried casting to an int, int* but when I try to get that to NSLog, I get error about an incompatible pointer type.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
返回的值是对象中正确位置的值; 只是类型不对。 对于
int
和BOOL
(但不是float
),您可以将指针强制转换为int
或>BOOL
,因为指针和整数的大小相同,并且它们可以相互转换:The value that is returned is the value from the right place in the object; just not the right type. For
int
andBOOL
(but notfloat
), you could just cast the pointer to anint
orBOOL
, since pointers and ints are the same size and they can be cast to each other:它可能将值装箱到 NSNumber 中。 您可以通过 NSLogging 返回的 id 的 className 来验证这一点,如下所示:
编辑:我在这里发现了另一个与此类似的问题:处理 object_getIvar 的返回值(id object, Ivar ivar)
从我自己的实验来看,我原来的假设是不正确的。 int 和 float 以及其他基元似乎作为实际值返回。 但是,最好使用 ivar_getTypeEncoding 来验证返回的值是否是您期望的类型。
It's probably boxing the value in an NSNumber. You can verify this by NSLogging the returned id's className, like so:
Edit: I found another question just like this one here: Handling the return value of object_getIvar(id object, Ivar ivar)
From my own experimentation, it would appear that my original assumption was incorrect. int and float and other primitives appear to be returned as the actual value. However, it would be appropriate to use ivar_getTypeEncoding to verify that the returned value is the type that you're expecting it to be.
您可以直接使用
object_getInstanceVariable
:(尚未测试)you can use
object_getInstanceVariable
directly: (haven't tested it)获取:
输出:
设置:
输出:
Getting:
Outputs:
Setting:
Outputs:
对于 ARC:
受此答案启发:object_getIvar 无法读取BOOL iVar 的值。
您必须对 object_getIvar 进行函数调用以获取基本类型 ivars。
我制作了一个有用的小宏来快速定义此类函数指针:
然后,对于基本类型,您需要指定对宏的调用(参数例如(long long,LongLong)将适合):
之后是用于接收 int(或指定的)变量类型变得可用:
For ARC:
Inspired by this answer: object_getIvar fails to read the value of BOOL iVar.
You have to cast function call for object_getIvar to get basic-type ivars.
I have made a small useful macro for fast definition of such function pointers:
Then, for basic types you need to specify calls to macro (params e.g. (long long, LongLong) will fit):
And after that a function for receiving int(or specified) variable type become available: