2

Possible Duplicates:
When to access properties with 'self'
In Objective-C on iOS, what is the (style) difference between “self.foo” and “foo” when using synthesized getters?

For example sake, I have a @property named obj and I @synthesize it. So when do I need to use [self.obj message] vs [obj message] in my implementation class.

Community
  • 1
  • 1
cantfindaname88
  • 195
  • 1
  • 6
  • 15
  • 1
    There's a search box in the upper right corner of the page. Use it. This question has been asked a dozen times before. – Dave DeLong Jun 20 '11 at 17:03

4 Answers4

2

Using self, the getter method will be called. Thus, any additional logic in this getter method is executed. This is especially useful when instance variables are lazy loaded through their getters.

I myself try to use self most of the time. Lazy loading is just an example, another thing is that with self, subclasses may override the getter to get different results.

Using self to set a variable is even more useful. It will trigger KVO notifications and handle memory management automatically (when properly implemented, of course)

Joost
  • 10,333
  • 4
  • 55
  • 61
1

Here are two great tutorials that cover this issue well:

Understanding your (Objective-C) self

When to use properties & dot notation

PengOne
  • 48,188
  • 17
  • 130
  • 149
1

When synthesize a property, the compiler declare a related ivar for you, in default, the ivar is the same as property name. I recommend use self.obj always to keep code cleaner, and avoid some potential bugs.

And I suggest you follow the good practice from Apple, @synthesize obj=_obj, the ivar will become _obj, when you mean to use property, this style force you to write self.obj, directly call obj will be error since the ivar is _obj.

Edit: automatically creating ivar for property is only in modern Objective-C runtime, it's safe in iOS SDK 4.0 and Mac OS X 10.6 above.

http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocProperties.html%23//apple_ref/doc/uid/TP30001163-CH17-SW1

For @synthesize to work in the legacy runtime, you must either provide an instance variable with the same name and compatible type of the property or specify another existing instance variable in the @synthesize statement. With the modern runtime, if you do not provide an instance variable, the compiler adds one for you.

cxa
  • 4,238
  • 26
  • 40
  • Properties are used to quickly declare efficient getters (and setters), no instance variable will be created. – Joost Jun 20 '11 at 16:44
  • @Joost That's true in the old Objective-C runtime, but in modern runtime, the property is really create an ivar for you. – cxa Jun 20 '11 at 16:49
  • Thanks for the documentation link, I revoked my downvote. – Joost Jun 20 '11 at 17:02