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,508
298
Hi,

In the stanford course Paul Hegarty prefers to use lazy instantiation. For instance he makes a private declaration of
Code:
@property (strong, nonatomic) (NSArray *)cards

and then he uses the getter to perform an initialization
Code:
- (NSArray *) cards
{
   if(!_cards) _cards = [[NSArray alloc]init]
   return _cards;
}

I'm cool with that. What I don't get though is that at another time Paul declares a public suit for a playingCard being:
Code:
 @property (strong, nonatomic) NSString *suit;

but in the implementation he doesn't perform this lazy instantiation. So I don't understand where the alloc init of the suit string happens? (suit being a pointer to an NSString - object which ought to get a place in the heap)
Code:
#import "PlayingCard.h"

@implementation PlayingCard
@synthesize suit = _suit;

- (void)setSuit:(NSString *)suit
{
    if ([@[@"♣︎", @"♠︎", @"♥︎", @"♦︎"]containsObject: suit]) {
        _suit = suit;
    }
}

- (NSString *)suit
{
    return _suit? _suit: @"?";
}
@end
 

MattInOz

macrumors 68030
Jan 19, 2006
2,760
0
Sydney
As I'm reading it the second example always requires the user of this object to pass a suit string to set the suit or it returns "?".

So the string returned is either passed in by the user and held, so is already created. Or it is provided by the string literal syntax @"?".
 

waterskier2007

macrumors 68000
Jun 19, 2007
1,871
228
Novi, MI
To summarize what Matt said, if the user has set the suit, and it is a valid suit (heart, diamond, spade, club) then the suit is set to what the user specified, and the getter would then return the suit (_suit). If it has not been set (or the user attempted to set it, but with an invalid suit type), the getter will return @"?"
 

grandM

macrumors 68000
Original poster
Oct 14, 2013
1,508
298
tx, I've understood the code
It's a bit disappointing to be honest how long it takes to master iOS...
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.