6

i have a question about using getters and instance variables. Let's see an example.

Suppose i have in a .h file:

@property (nonatomic,strong) NSString *name

and in the .m file i synthesize that variable in this way:

@synthesize name = _name;

Now my question is: what's the difference between use:

[self.name aMethod]

and

[_name aMethod]

Thanks!

justin
  • 104,054
  • 14
  • 179
  • 226
Gerardo
  • 5,800
  • 11
  • 66
  • 94

3 Answers3

8

The first one accesses the ivar through the getter method. The second directly accesses the ivar. Since it's a simple, synthesized property, there's not much difference except that the first makes an additional method call. However, if the property were atomic, or dynamic, or the getter method were complicated, there'd be a difference in that the first one would actually be atomic while the second wouldn't and the first would actually trigger any complicated logic in the getter while the second wouldn't.

In simplest terms, the compiler re-writes the first call to:

[[self name] aMethod]

while the second call is simply left as-is.

Jason Coco
  • 77,985
  • 20
  • 184
  • 180
1
[self.name aMethod]

is equivalent to

[[self name] aMethod]

Thus a getter is called and the message is sent to its result.

In your case, the visible result will be the same.

However, it may not be a case if getter wasn't trivial (i.e. synthesized).

Krizz
  • 11,362
  • 1
  • 30
  • 43
0

The first calls through the getter -- it is equal to [[self name] aMethod]. The second just uses direct access.

You should generally favor using the accessors, but there are times where you should deviate from that. the most common occurrence is while in partially constructed states, such as your initializer and dealloc. the reason is that you should be carefully constructing or destroying your state, and not interested your object's interface semantics - that is, using the accessors can have negative behavioral and semantic side effects.

A more complete list of reasons can be found here: Why would you use an ivar?

Community
  • 1
  • 1
justin
  • 104,054
  • 14
  • 179
  • 226