Advice on good programming practice, please

Discussion in 'Mac Programming' started by mdeh, Mar 5, 2009.

  1. mdeh macrumors 6502

    Jan 3, 2009
    From Kochan's book, an example ( barebones)

    @interface  AddressCard:NSObj......   <NSCopying>
    NSSTring * name;
    @property ( copy, nonatomic)  NSString *name;
    In the addresscard's implementation

    -(void) encodeWithCoder: (NSCoder *) encoder
    [encoder encodeObject: name forKey........]

    From advice I have received here before, I am assuming, perhaps as I incorrectly understood the advice :) that invoking "name" in the encodeWithCoder method, **directly** uses name, as opposed to using the invocation ( and therefore the accessor).

    Now, if this is true, what is the best practice here. When would I use "self" vs what what I have written above?

    Thanks as always
  2. North Bronson macrumors 6502

    Oct 31, 2007
    San José
    In your case, I would find myself using [self name] to access your NSString.

    One cool thing about using your getter method is that it you have a little control over how you can load your instance variable.

    If I have an NSArray called myVeryLargeArray, I can write a getter method that loads this array if someone asks for it (if nobody ever asks for it, it just remains nil). This is a lazier approach than loading it somewhere like my init method.

    You wouldn't want to use a getter method *inside* of your getter method. If you follow the advice to load resources with your getters, you can also go ahead and access directly in the dealloc method of your class (since you are releasing the object anyway, why load it with a getter method?).

    Another thing is that it can remove a layer of ambiguity in your methods. If your style is to *always* use getter methods when you can, then if you see a line like:

    [encoder encodeObject: name forKey. . . ]

    then it can help to make things a little clearer that name is *not* an instance variable of the class itself. If your method is several pages long, it helps to get the point across -- at least for me.
  3. mdeh thread starter macrumors 6502

    Jan 3, 2009

    Thank you for all your insights. Much appreciated.

Share This Page