Reputation: 15698
Consider the following implementation of a few classes:
.h file implementations of three different classes
//superClass.h
...
@interface superClass
//Insert useful code
@end
//subClass.h
...
@interface subClass : superClass
//Insert useful code
@end
//Another class that uses various sub-classes of superClass
@interface anotherClass
{
superClass* myObj;
}
@property (strong, atomic) superClass* myObj;
@end
.m file implementation of anotherClass
@implementation anotherClass
@synthesize myObj;
...
//All of the code that uses the myObj property...
...
@end
How can I set an instance of subClass
to an instance of property anotherClass.myObj
?
In my specific case, I would like to define a property that is a UIViewController
. I have multiple sub-classed, UIViewControllers and I need to be able to swap them in and out on a specific property within my iOS app.
Each time I've tried to set one of my child UIViewControllers to my UIViewController
property, the app crashes. However, if I re-define the property to be an instance of one of child classes and then instantiate a sub-class, it works perfectly. I really need to have the ability to swap these controllers in and out. How can I do this?
UPDATE
Well, apologies to all who have been looking at this. After getting an obvious answer, I decided to re-write all of the associated code. I created a new property, with a different name, commented out all of my assignment code and re-wrote it to point to the new property. It's working just as it should. I'm not sure why this wouldn't work the first time but it is now behaving as it should. I'm still not clear, however, why my app was crashing.
Upvotes: 0
Views: 374
Reputation: 125017
Just do the assignment. Every instance of subClass
is also an instance of superClass
. That's subtype polymorphism in action.
Upvotes: 1