Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

grandM

macrumors 68000
Original poster
Oct 14, 2013
1,551
309
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?
 
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.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.