Saturday, 17 August 2013

Objective C Subclassing: Is this proper?

Objective C Subclassing: Is this proper?

So I'm working on an iPad game using the cocos2d framework.
My game requires different buildings to be spawned at the beginning of a
"level". The user gets to choose which buildings they want to use.
An important functionality here is that different buildings will perform
different actions when pressed.
I have a parent class that looks something like this:
BaseBuilding.h
@interface BaseBuilding : NSObject {
CGRect _hitBox;
NSString *_name;
CCSprite *_sprite;
int _identifier;
int _health;
int _coolDownDuration;
}
@property (atomic, retain) CCSprite *sprite;
@property (atomic, assign) int identifier;
@property (atomic, assign) int health;
- (void) onBuildingPressed;
- (id) initWithName:(NSString*)baseName;
- (id) initBuilding;
- (CGRect) hitBox;
- (void) sustainDamage;
So most of my buildings are very similar. Each building has their own
initBuilding method which overrides the parent. The initBuilding method
calls the super initWithName method which then looks up a plist with
information about that building (sprite name, etc).
Each building also has their own onBuildingPressed method, which also
overrides the parent method. This is very important functionality.
The part that I'm having trouble with:
I want to spawn the buildings based on what the player selects. What I'm
currently doing is something like this:
BaseBuilding *building;
switch (choice) {
case 1:
building = [BuildingX alloc];
[building initBuilding];
break;
case 2:
building = [BuildingY alloc];
[building initBuilding];
break;
case 3:
building = [BuildingZ alloc];
[building initBuilding];
break;
}
return building;
Since BuildingX, BuildingY, BuildingZ are all subclasses of BaseBuilding,
initBuilding does call the correct method.
Later on I can call [rightBuilding onBuildingPressed]; and it works as
expected.
BuildingX has a removeAmmo method that the other buildings don't have, so
I have to do this to call it: [(BuildingX*)centerBuilding removeAmmo].
Is this proper, or this a better way of doing this?

No comments:

Post a Comment