I added a set of classes to an array, all which I know have the same superclass:
[array addObject:[Africa class]];
[array addObject:[Brazil class]];
[array addObject:[France class]];
Later, I want to get the class object and call a superclass class method on it. Something like this:
Class class = [array objectAtIndex:1];
(Country class) specificClass = class;
I've tried a variation of different ideas, but can't figure out how to put that last line in code.
If I get you right you want a variable pointing to a class object, statically typed to a concrete class.
This not possible in Objective-C; there are no strongly typed class pointers.
Class class
is the best you can do.You can send any known class method to a
Class
typed variable...... without making the compiler complain. Of course some of the examples might fail at runtime.
With a proper design pattern, you shouldn't need to know which country you are working with.
Start by creating an
AbstractCountry
class that declares (and provides stub implementations) of all the methods your countries need to generically respond to (i.e. countries can be more specific).Then subclass that
AbstractCountry
for each individual country.Then:
If you need behavior that only exists on a single country, then either push a stub implementation up (which wouldn't be terribly elegant) or test for response to selector (also not elegant) or cast appropriately (fragile).
Of course, all of this begs the question of why you have classes for this and not instances (though the instance design would be the same; consider something like UIControl and all the subclasses -- the control provides the abstract behavior of controls whereas the subclasses implement specific kinds of controls by oft overriding the abstract methods).
Usually in Objective-C you would call a method like so:
So in your case, let's pretend that your superclass (I'm assuming "Country") has a method to set the population or something, it would look like: