object_setClass到更大的类 [英] object_setClass to bigger class

查看:141
本文介绍了object_setClass到更大的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 object_setClass(id对象,Class cls)更改某些对象的类。我正在将类更改为原始类的子类。然后我设置一些仅在子类中定义的属性,并且似乎工作正常。

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.

我有点惊讶,这是有效的,因为 object_setClass ,据我所知,不会重新分配对象,它只会更改 isa 指针。如果子类实例比原始类实例大得多(意味着有更多的ivars),我看不到对象如何按预期工作。

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)?

这是强大的,还是可能在某些情况下崩溃? p>

Is this robust, or could it crash under some circumstances?

推荐答案

可能会崩溃。从运行时的源代码可以看出,这里,它真的只是交换 isa 指针。

It could crash. As can be seen in the source code of the runtime here, it really just swaps the isa pointer.

如果您真的想将 isa 交换到 isa 具有更多ivars的子类,您应该使用 class_createInstance 与非零 extraBytes

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.

这篇关于object_setClass到更大的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆