0

I have a superclass called City and a bunch of subclasses that inherit from this class. For example London and NewYork. Each of these subclasses have their own unique methods and instance variables.

When my app launches I geocode the current location and instantiate the subclass depending on which city I'm currently in.

Right now I have multiple properties defined to access these classes, so

@property (nonatomic, strong) London *london; @property (nonatomic, strong) NewYork *newYork; ... ... 

I will only ever need one object of this type in existence at any one time so would only like one property defined to access this object. Something like

@property (nonatomic, strong) City *city; 

Is there a way I can dynamically create the subclass I require without having to declare multiple properties?

4
  • 8
    It's a little worrisome that you have London and NewYork classes. Why do you need specialized subclasses? Why not a generic City class that you can then query (similar to a dictionary, perhaps?) for specific information? Commented May 19, 2012 at 15:55
  • @DaveDeLong +1 What he's got up there sounds like a terrible design pattern. Commented May 19, 2012 at 16:18
  • @DaveDeLong I thought subclassing worked best here as each city has it's own unique instance variables and methods that only apply to that particular city. For generic things like population, land mass etc, these are all inherited from the superclass. Commented May 19, 2012 at 17:18
  • 1
    @KJF can you give an example of some of this unique information? Commented May 19, 2012 at 17:27

2 Answers 2

2

You can definitely implement subclasses in Objective-C. You could do the following to instantiate a city:

self.city = [[NewYork alloc] init]; 

To call city-specific methods:

if ([self.city isKindOfClass:[NewYork class]]) { // call some NewYork methods e.g.. [(NewYork *)self.city doNewYorkThing]; } else if ([self.city isKindOfClass:[London class]]) { // call some London methods e.g. [(London *)self.city doLondonThing]; } 

The methods "isKindOfClass:", "isMemberOfClass:", "conformsToProtocol:" and "respondsToSelector:" are useful class methods for you to get familiar with.

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

1 Comment

Sidenote: you'll get compiler warnings when calling subclass-specific methods unless you cast to the subclass or to id.
1

"dynamically" is a flexible concept. :) You can certainly write something like...

self.city = [[London alloc] init]; 

...and then use any methods defined in City. You will get the overridden version of those methods if London defines its own implementation. If you really, really know it's a London object, you can also do:

[(London *)city somethingSpecial]; 

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.