Alex Rivera | Logout

Should I Use self Keyword (Properties) In The Implementation?

Asked 2009-06-26T22:24:48.940
11

I believe I understand properties for the most part. My question is, if I have a property for an instance variable, and I am setting or retrieving it from within a method in my implementation file, should I use self.myProperty or just myProperty? I know either one works, but I have seen mixed conventions, sometimes code accesses the variable directly and other times through the property.

Is there a technical reason for doing this? Is it just convention/personal preference? And I'm not referring to the instances where the parameter name of a method collides with the instance variable name, which might be one reason to use the property (At least, in other languages, I don't know about this one). I assume that when one uses the property within the implementation, they want to take advantage of the way in which they declared the property (i.e. nonatomic, retain), so for example in a method, one can do:

self.myProperty = [someObject someAutoReleasedObject];

instead of:

myProperty = [[someObject someAutoReleasedObject] retain];

Is this the reason? So are there only certain situations in which it would be good to use the property?

I'm new to Objective-C, and this is one of the few things that has me confused. So far I've just accessed the instance variable directly, under the most likely false assumption that going through the property actually calls/sends a method/message and adds unnecessary overhead. I'm pretty sure I'm wrong with this, but even if the difference in overhead is negligible (If there even is any), why would one choose to add it in when one can simply directly access the variable?

I'm pretty sure I'm wrong in my thinking, which is why I'm asking here.

Edit
Report

1 Answer

0

If you're exposing the property to the outside world and you're using it internally you should be using the property throughout your code. The reason is encapsulation. Say you have an "Id" property for SomeObj. Say at some point you decide to replace the way Id behaves (maybe you started with Id being a member var of the class, and through evolution it becomes a piece of data that is retrieved from the database). Now you have to go through your class implementation and replace all of the references to the member var with database calls. If you had self.Id, you'd just have to override the getter.

answered 2009-06-26T22:39:18.037

Your Answer