views:

42

answers:

1

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  A: 

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.

Yuji
@Yuji: thanks, that's what I was afraid of and it makes sense of course. I don't see how your solution would help, because I don't want to create a new object. (I can't, because the object is a readonly property of another class.)
Felixyz
If it's your code, you can arrange the property to be created with the extra bytes so that you can safely change the class later. But I don't think it's a good idea to swap the class of a readonly property! Why are you doing that?
Yuji
I thought it was a clever little hack to modify a view loaded from a nib. But I'll resort to more standard methods.
Felixyz