object_setClass 到更大的类
我正在使用 object_setClass(id object, Class cls)
更改某些对象的类。我正在将该类更改为原始类的子类。然后我设置了一些仅在子类上定义的属性,事情似乎工作正常。
我对这有效感到有点惊讶,因为据我所知,object_setClass 不会重新分配对象,它只会更改 isa 指针。如果子类实例比原始类实例大得多(意味着有更多的 ivars),我不知道该对象如何按预期工作。
这是否仅仅因为内存中的对象之间存在大量缓冲内存(由于对齐等原因)而起作用?
这是否可靠,或者在某些情况下会崩溃吗?
I am changing the class of some objects using object_setClass(id object, Class cls)
. I am changing the class to a subclass of the original class. Then I set some properties that are only defined on the subclass, and things seem to work fine.
I was a bit surprised that this worked, because object_setClass
, as far as I understand, doesn't reallocate the object, it only changes the isa
pointer. If the subclass instances are considerably larger (meaning having many more ivars) than the original class instances, I don't see how the object can work as expected.
Does this work only because there is a lot of buffer memory between objects in memory (due to alignment etc)?
Is this robust, or could it crash under some circumstances?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它可能会崩溃。从运行时的源代码中可以看出 这里< /a>,它实际上只是交换了
isa
指针。如果您确实想将
isa
交换为具有更多 ivars 的子类的isa
,您应该使用class_createInstance
带有非零的extraBytes
。It could crash. As can be seen in the source code of the runtime here, it really just swaps the
isa
pointer.If you really want to swap the
isa
to anisa
of a subclass with more ivars, you should useclass_createInstance
with nonzeroextraBytes
.不要使用更大的子类,而是使用 objc_setAssociatedObject 和 objc_getAssociatedObject 将附加对象动态附加到现有的固定大小对象。
Instead of using a larger subclass, use
objc_setAssociatedObject
andobjc_getAssociatedObject
to attach dynamically additional objects to your existing fixed-size object.