views:

498

answers:

2

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.

A: 

I think this is, as you say, dirty.

I suspect it will work if:

  • The newly assigned class is a subclass of the real class.
  • The new class doesn't add any member variables.

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.

Darron
A: 

It's really bad form to change these, and it makes all sorts of assumptions about runtime behaviour -- you're much better off using the runtime functions although they don't provide you with a mechanism to directly change the class.

olliej