Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it defined behavior to change an Objective-C object's isa?

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.

like image 310
Adam Rosenfield Avatar asked Nov 06 '22 22:11

Adam Rosenfield


2 Answers

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.

like image 41
benzado Avatar answered Nov 15 '22 13:11

benzado


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.

like image 106
Darron Avatar answered Nov 15 '22 13:11

Darron