IOS when using an instance variable or getter method

I have a question about using getters and instance variables. Consider an example.

Suppose I have a .h file:

@property (nonatomic,strong) NSString *name 

and in the .m file I synthesize this variable as follows:

 @synthesize name = _name; 

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

 [self.name aMethod] 

and

 [_name aMethod] 

Thanks!

+6
source share
3 answers

The first gets access to ivar through the getter method. The second directly refers to ivar. Since this is a simple, synthesized property, there are not many differences, except that the former calls an additional method call. However, if the property was atomic or dynamic, or the getter method was complex, there would be a difference in the fact that the first would be actually atomic and the second not, and the first would actually trigger any complex logic in and the second not.

Simply put, the compiler rewrites the first call:

 [[self name] aMethod] 

and the second call is simply left as is.

+8
source
 [self.name aMethod] 

equivalently

 [[self name] aMethod] 

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

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

However, this may not be the case if the getter was not trivial (i.e. synthesized).

+1
source

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

You should generally endorse the use of accessories, but there are times when you should deviate from it. the most common occurrence is in partially constructed states like your initializer and dealloc . the reason is that you must carefully design or destroy your state and not be interested in the semantics of the object interface, that is, the use of accessors can have negative behavioral and semantic side effects.

A more complete list of reasons can be found here: Why are you using ivar?

0
source

Source: https://habr.com/ru/post/907720/


All Articles