changing a getter through inheritance

Discussion in 'iOS Programming' started by grandM, Jun 29, 2014.

  1. grandM macrumors 6502a

    grandM

    Joined:
    Oct 14, 2013
    #1
    Hi guys, I wonder why the following isn't allowed:

    this is Card.h

    Code:
    #import <Foundation/Foundation.h>
    
    @interface Card : NSObject
    
    @property (nonatomic) NSUInteger numberOfMatchingCards;
    
    @end
    
    In the implementation card.m has this code:
    Code:
    - (NSUInteger)numberOfMatchingCards
    {
        if(!_numberOfMatchingCards)_numberOfMatchingCards = 2;
        return _numberOfMatchingCards;
    }
    
    SetCard is a subclass of Card so in the implementation of SetCard I would have liked to do this:
    Code:
    - (NSUInteger) numberOfMatchingCards
    {
        if(!_numberOfMachingCards)_numberOfMatchingCards=3;
        return _numberOfMatchingCards;
    }
    
    Instead the author goes through init in the sample code:
    Code:
    - (instancetype) init
    {
      self = [super init]
      if(self){
        self.numberOfMatchingCards=3;
      }
    
      return self;
    }
    
    Why can't I use the lazy instantiation in SetCard.m and why must I go via init?
     
  2. dejo Moderator

    dejo

    Staff Member

    Joined:
    Sep 2, 2004
    Location:
    The Centennial State
    #2
    What author? Are you referencing something from a book? If so, please be as specific as possible. That is: give us the book's name, author, edition and, if possible, chapter and page number.
     
  3. grandM thread starter macrumors 6502a

    grandM

    Joined:
    Oct 14, 2013
    #3
    author

    I was looking at the solutions at http://cs193p.m2m.at/cs193p-assignment-3-task-2-fall-2013-14/#comment-133519

    I suspect though that one can't use lazy instantiation because numberOfMatchingCards is a private instance variable of the mother class. Hence it can only be accessed using the property getter and setter method. I reckon there isn't a way to access an instance variable of the mother class another way. It did surprise me a bit because numberOfMatchingCards is a public variable of the mother class.

    I don't like to have to hand it a value through init though.
     

Share This Page