object_setClass to bigger class

流过昼夜 提交于 2019-12-03 16:38:47

问题


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?


回答1:


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 an isa of a subclass with more ivars, you should use class_createInstance with nonzero extraBytes.




回答2:


Instead of using a larger subclass, use objc_setAssociatedObject and objc_getAssociatedObject to attach dynamically additional objects to your existing fixed-size object.



来源:https://stackoverflow.com/questions/3346427/object-setclass-to-bigger-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!