views:

175

answers:

3

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!

+2  A: 

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.

Tom Duckering
An example of this idiom is `[NSMutableArray arrayWithArray:someArray]`
cobbal
A: 

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);
Nicholas Riley
Beware, if anything has a reference to a, that reference will now be invalid.
rpetrich
A: 

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.

rpetrich