Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C using inherited variables & overriding inherited properties

Tags:

objective-c

(ARC is enabled)

lets say I have a class names BasicGameCard in it declared the following property:

@property (nonatomic) NSUInteger cardValue; 

Then I create a derived class WarGameCard : BasicGameCard.

WarGameCard extends with a suit property and wishes to use the inherited cardValue to represent its rank Questions:

  1. how can i use/call in WarGameCard class the variable _cardValue without using the property?

    a) writing _cardValue in WarGameCard: results in compiler error (i guess there is no protected Access modifier in objective-c and the variable is private)

    b) can't use self.cardValue it will compile but will cause an infinite loop calling the setter

    c) tried to write the following in WarGameCard: @synthesize cardValue = _cardValue; but when debugging i see 2 different variables one of super class and one of the derived each with different value

  2. What is the right way to override inherited properties

like image 705
liv a Avatar asked Feb 25 '13 00:02

liv a


1 Answers

In your subclass, use the inherited accessors cardValue and setCardValue: to get and set the inherited value. You don't need to override the value; you just need to use it.

Once your subclass consistently uses the accessors, then you can override the accessors if you want. For example

 - (void) setCardValue: (NSInteger) newValue
 {
      [super setValue: newValue];
      [self celebratePromotion];
 }

You're correct: in Objective C there's no protected inheritance. But modern objective-C uses accessors far more extensively than C++. In fact, outside constructors and destructors and (arguably) accessors, you should never touch instance variables directly.

like image 71
Mark Bernstein Avatar answered Sep 20 '22 22:09

Mark Bernstein