(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:
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
What is the right way to override inherited properties
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With