The difference between self.var and just var

What is the difference between using self.var and just var in the Objective-C class? Are there any advantages or dangers to this or that?

+7
source share
3 answers
 foo = self.var; self.var = foo; 

conceptually identical

 foo = [self var]; [self setVar: foo]; 

Thus, using dot notation, you really send messages to yourself.

 foo = var; var = foo; 

conceptually coincides with

 foo = self->var; self->var = foo; 

Therefore, not using dot notation to access an instance variable is the same as treating yourself as a pointer to a C structure and directly accessing string fields.

In almost all cases, it is preferable to use a property (either point or message notation). This is because a property can be made to automatically fulfill the need to save / copy / release to stop a memory leak. Alternatively, you can use the value of a key value with a property. Subclasses can also override properties to provide their own implementation.

Two exceptions for using properties are setting ivar in init and releasing it in dealloc. This is because you almost certainly avoid accidentally using subclass overrides in these methods, and you don't want to trigger KVO notifications.

+5
source

self.var calls the var property. Behind the scenes, Objective-C automatically generates a getter for properties (or you can do it yourself if that is the case), so self.var uses this getter. The regular var accesses the instance variable directly (i.e., it does not go through getter to get the value).

+6
source
0
source

All Articles