2

Say that I have Class A and Class B. Class B is a subclass of Class A. Class A contains some properties and then Class B extends the Class A superclass by adding some additional properties, specific to that subclass. I have created a Class A object and now wish to convert the object to be a Class B type object at runtime, so that I can add data to the additional properties provided by Class B. Is there any way to do this in Objective-C? Thanks!

1
  • This is dangerous; you really shouldn't do this. Commented Feb 13, 2010 at 9:00

3 Answers 3

3

Why don't you write a constructor for Class B that takes a Class A as a argument with addition properties required by class B.

Why don't you just create a class B in the first place? It does sound a bit strange that you'd want to do this. Perhaps you can give us some more concrete details about classes A & B and what you're doing with them.

Sign up to request clarification or add additional context in comments.

1 Comment

An example of this idiom is [NSMutableArray arrayWithArray:someArray]
1

You can't convert it in place because an instance of class B is bigger than an instance of class A (assuming the additional properties are stored in ivars). Objective-C doesn't have the ability to relocate objects.

If you're happy to make a copy of the object (i.e., you're sure there are no references to it or can update them), you could do something like this with the Objective-C runtime functions:

newB = object_copy(a, class_getInstanceSize(B)); object_setClass(newB, B); object_dispose(a); 

1 Comment

Beware, if anything has a reference to a, that reference will now be invalid.
0

The simplest way is to replace alloc on class A to actually return class B.

@implementation ClassA (MyCategory) + (id)alloc { if (self != [ClassB class]) return [ClassB alloc]; return [super alloc]; } @end 

Of course, doing this is generally a really bad idea.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.