Andrew Robinson
Andrew Robinson

Reputation: 3444

Can I override a property's class with a subclass of the class in my .m file?

Given that I have a Game class:

@interface Game : NSObject

with a CutthroatGame subclass:

@interface CutthroatGame : Game

If I have a property like this in my ViewController .h file:

@property (strong) Game *game;

Can I safely override the property like this in my ViewController .m file:

if (_playerCount == 3) {
    _game = [[CutthroatGame alloc] init];
else {
    _game = [[Game alloc] init];   
}

Edit: If this is supposed to work, how do I deal with the below error?

CutthroatGame defines a number of additional properties, such as:

@property (strong) Player *opponent2

When I try to access them using the _game property of my ViewController, I get the following error:

 _game.opponent2 = [players objectAtIndex:0]; -- ERROR: Property 'opponent2' was not found on object of type 'Game *'

Upvotes: 2

Views: 73

Answers (2)

Eric Qian
Eric Qian

Reputation: 2256

I think the reason why you got that error is because:
@property (strong) Game *game;
The type of game is Game not CutthroatGame. So when you try to do _game.opponent2 = [players objectAtIndex:0]; it gives you an error.
You can try this:
((CutthroatGame *)_game).opponent2 = [players objectAtIndex:0];

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727137

Absolutely! That is what Liskov substitution principle is about. If you properly subclass CutthroatGame from Game, you will have no problem substituting Game with its subclass.

Upvotes: 1

Related Questions