7

What is the difference between using self.var vs. just var in an Objective-C class? Are there benefits or dangers to one or the other?

jscs
  • 63,694
  • 13
  • 151
  • 195
MyNameIsEarl
  • 73
  • 1
  • 3
  • possible duplicate of [What's the difference between using obj-c accessors and using dot syntax?](http://stackoverflow.com/questions/1258360/whats-the-difference-between-using-obj-c-accessors-and-using-dot-syntax) (Not an exact duplicate, but it's been brought up many times before) – Dave DeLong Jan 07 '11 at 17:32
  • 2
    I apologize about that. I would delete my question but the answers below are quite good. – MyNameIsEarl Jan 07 '11 at 17:37
  • 1
    Actually, I just noticed I don't have the option to delete it anymore. Sorry dor the duplicate. – MyNameIsEarl Jan 07 '11 at 17:42

3 Answers3

6

self.var calls the property for var. Behind the scenes, Objective-C automatically generates a getter for properties (or you can make one yourself, if so inclined), so self.var uses that getter. Plain var accesses the instance variable directly (i.e., it doesn't go through the getter to get the value).

mipadi
  • 398,885
  • 90
  • 523
  • 479
  • What is the benefit of going through the generated getter? – MyNameIsEarl Jan 07 '11 at 16:35
  • 1
    @MyNameIsEarl: Your getter could conceivably modify the ivar in some way (or even provide an ivar for a property that doesn't exist, if you wrote your own getter). Going through the getter also fires off KVO notifications, whereas direct access of the ivar doesn't. – mipadi Jan 07 '11 at 16:49
5
foo = self.var;
self.var = foo;

is conceptually identical to

foo = [self var];
[self setVar: foo];

So using dot notation, you are really sending messages to self.

foo = var;
var = foo;

is conceptually the same as

foo = self->var;
self->var = foo;

So not using dot notation to access an instance variable is the same as treating self as a pointer to a C struct and accessing the struct fields directly.

In almost all cases, it is preferable to use the property (either dot notation or message sending notation). This is because the property can be made to automatically do the necessary retain/copy/release to stop memory leaks. Also, you can use key value observing with a property. Also subclasses can override properties to provide their own implementation.

The two exceptions to using properties are when setting an ivar in init and when releasing it in dealloc. This is because you almost certainly want to avoid accidentally using a sub class override in those methods and you don't want to trigger any KVO notifications.

JeremyP
  • 84,577
  • 15
  • 123
  • 161
0

Duplicate of

and probably about a dozen others that you could've found in about 15 seconds by using the "Search" box up in the top right corner of the site.

Community
  • 1
  • 1
Dave DeLong
  • 242,470
  • 58
  • 448
  • 498