In Objective-C, you can change an object's dynamic type at runtime by assigning to it's isa
member variable:
id object = ...;
object->isa = [SomeClass class];
Is this undefined behavior? I'm currently doing this as a kludge for something else, and it appears to be working, but I feel so dirty doing it this way. The new class I'm setting doesn't add any member variables, it just overrides one method and adds a new one, so the class size is the same. I feel like if I changed the object size, much badness would result.
The Objective-C runtime now provides a function to do this: object_setClass
. The documentation doesn't say what restrictions there are, but (as others have stated) I imagine you would want to restrict the new class to a class with exactly the instance variable layout as the original class.
I think this is, as you say, dirty.
I suspect it will work if:
But I'll admit I don't know the nuts-and-bolts implementation of your Objective-C runtime system. I just know what makes sense to me for an implementation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With