lazy instantiation

Discussion in 'iOS Programming' started by grandM, Apr 21, 2014.

  1. grandM macrumors 6502a

    grandM

    Joined:
    Oct 14, 2013
    #1
    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
    
     
  2. MattInOz macrumors 68030

    MattInOz

    Joined:
    Jan 19, 2006
    Location:
    Sydney
    #2
    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 @"?".
     
  3. waterskier2007 macrumors 68000

    waterskier2007

    Joined:
    Jun 19, 2007
    Location:
    White Lake, MI
    #3
    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 @"?"
     
  4. grandM thread starter macrumors 6502a

    grandM

    Joined:
    Oct 14, 2013
    #4
    tx, I've understood the code
    It's a bit disappointing to be honest how long it takes to master iOS...
     
  5. waterskier2007 macrumors 68000

    waterskier2007

    Joined:
    Jun 19, 2007
    Location:
    White Lake, MI
    #5
    This isn't really an iOS specific concept. It is really just setters and getters, which exist in many languages
     

Share This Page