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

mdeh

macrumors 6502
Original poster
Jan 3, 2009
345
2
From Kochan's book, an example ( barebones)

Code:
@interface  AddressCard:NSObj......   <NSCopying>

{

NSSTring * name;
}
@property ( copy, nonatomic)  NSString *name;

In the addresscard's implementation

Code:
-(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 self.name 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
 

North Bronson

macrumors 6502
Oct 31, 2007
395
1
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.
 

mdeh

macrumors 6502
Original poster
Jan 3, 2009
345
2


Thank you for all your insights. Much appreciated.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.