The difference is simple: Using self.label = [[UILabel alloc] init]
will actually invoke the method [self setLabel:[[UILabel alloc] init]]
, and using _label = [[UILabel alloc] init]
will directly assign the value to the instance variable.
In practice what this means is that using the dot syntax is usually the best as the method invoked probably handles a lot of stuff for you, including:
- Memory management: For example, if you declare a property with attribute 'strong' or 'retain', then the method invoked should retain the object assigned.
- Key-Value Coding notifications: Maybe the class is key-value coding compliant for the property, which means the invoked method will notify the changes to observer objects.
Why would you not use the dot syntax? There are two potential reasons:
- To avoid side effects: A good practice is to not use the dot syntax inside an initializer method. This is because we want to assign the value but don't want the other side effects of the invoked method for safety reasons.
- Performance: This is probably rare, but maybe you are trying to implement a method with high performance and using instance variables directly can save the cost of invoking a method.
If you want to know more, I recommend reading this iOS guide which describes in more detail the ideas I mention here.