Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS when use instance variable or getter method

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!

like image 617
Gerardo Avatar asked Feb 05 '12 21:02

Gerardo


People also ask

What is the difference between property and instance variable IOS?

A property can be backed by an instance variable, but you can also define the getter/setter to do something a bit more dynamic, e.g. you might define a lowerCase property on a string which dynamically creates the result rather than returning the value of some member variable.

Why do we use instance variables?

An instance variable is a class property that can be different for each object. You create an instance variable by declaring it in the class definition, outside of any method. Instance variables are important because they allow each object to have its own copy of the data.

Can we use instance variable in method?

Instance variables are declared inside a class but not within a method. class Horse { private double height = 15.2; private String breed; // more code... } Local variables are declared within a method. Local variables MUST be initialized before use!


2 Answers

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.

like image 105
Jason Coco Avatar answered Sep 28 '22 08:09

Jason Coco


[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).

like image 36
Krizz Avatar answered Sep 28 '22 08:09

Krizz