Matching instance variable names in property synthesis

When synthesizing properties in Objective-C, it is recommended that you not just write:

@synthesize window; 

but rather

 @synthesize window = _window; 

The reason is that you do not want your instance variable to be named just like your getter method, or "bad things can happen."

I have always used @synthesize var1, var2, etc in my applications without the β€œbad things”. What bad things can be?

+4
source share
2 answers

The bad things that happened, especially in the days before ARC, when people assigned objects to the iVar store instead of a property. If this was done by accident, then the memory management implied by the synthesized installer will not be applied, which will lead to leaks or premature releases.

I use this in a simple way, but now I use prefixes. I no longer declare my iVar, I let the modern runtime take care of this for me. I use prefixes so that I do not accidentally use iVar as a local variable.

Also, I usually treat my properties as self.iVar almost everywhere in my classes. This is so that I can use lazy loaded properties whenever I want, without worrying about which ones are not lazily loaded.

+5
source

The biggest reason for using advanced underscore in instance variables (like _myProperty) is that when people read leading underscore code, they know that you are using an instance variable and not a local variable, a global variable, or forgot to write "I" . like self.myProperty, and that you did it on purpose.

Prior to ARC, _myProperty will not do any reference counting, while self.myProperty will (for "save" / "strong" properties). With ARC, when you use the "copy" properties, _myProperty does reference counting, but does not copy, so there is still some difference. The most important difference is that _myProperty will not fire any watchers.

0
source

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


All Articles