*(id *)((char *)object + ivar_getOffset(ivar)) 和 object_getIvar(object, ivar) 之间有什么区别
ivar_getOffset 返回偏移量 实例变量。
ptrdiff_t ivar_getOffset(Ivar ivar) 讨论 对于实例变量 输入 id 或其他对象类型,调用 object_getIvar 和 object_setIvar 而不是使用此偏移量来访问 直接实例变量数据。
在runtime.h中声明
这是为什么呢? object_getIvar 对对象类型有什么作用?
编辑:将问题从下标 (void *) 更改为 (id *)。
According the Objective-C runtime reference:
ivar_getOffset
Returns the offset of
an instance variable.ptrdiff_t ivar_getOffset(Ivar ivar)
Discussion For instance variables of
type id or other object types, call
object_getIvar and object_setIvar
instead of using this offset to access
the instance variable data directly.Declared In runtime.h
Why is this? What does object_getIvar do to object types?
EDIT: changed question from subscripting (void *) to (id *).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在获取 ivar 的值时,这两种方法没有区别。您可以通过查看 Apple 开源 Obj-C 运行时代码。
object_setIvar()
的作用不仅仅是分配对象指针的偏移量。小心地调用垃圾收集运行时函数 objc_assign_ivar() 来执行实际的分配。将来可能会为这些功能添加更多魔力;一般来说,您应该在任何给定时间使用可用的最高级别的 API。
There is no difference between those two approaches when it comes to getting the value of the ivar. You can verify this by looking at
object_getIvar()
's implementation in Apple's open-source Obj-C runtime code.object_setIvar()
does more than just assign to an offset from the object pointer. It is careful to call through to the garbage-collection runtime functionobjc_assign_ivar()
to perform the actual assignment.More magic might be added to either of these functions in future; in general, you should use the highest-level API available at any given time.
也许并不是
object_getIvar
做了不同的事情,而是id
类型的实例变量或其他对象类型很常见,并且调用ivar_getOffset
并附加将结果转换为object
的值,然后转换为适当的类型要麻烦得多。请注意,根据 C99 标准中的以下信息(重点是我的),您无法可靠地增加
void *
的值:要将指针增加任意数字,可以使用
char *
代替。Perhaps it's not that
object_getIvar
does something different, but that instance variables of typeid
or other object types are commonplace, and that callingivar_getOffset
and appending the result to the value ofobject
and then casting to the appropriate type is much more cumbersome.Note that you cannot reliably increment the value of a
void *
, based on the following information from the C99 standard (emphasis mine):To increment a pointer by an arbitrary number, you can use
char *
instead.