IVars, with and without yourself?

I just wonder what role the object plays. I understand that the entry [[self dataForTable] count] refers directly to the iVar contained in this object. But if you are missing self-control and directly specifying iVar [dataTable count] , how is this different from what you protect using self, you just need to explicitly specify iVar, and not some similar local variable?

 @implementation ViewController @synthesize dataForTable; ... NSUInteger dataCount = [[self dataForTable] count]; 

much appreciated

Gary.

0
source share
2 answers

The entry [[self dataForTable] count] does not apply directly to iVar. There are some backstage stuff ...

If you use ivar in your code without yourself, this is direct access to ivar. If you use either [self someIvarName] or self.someIvarName, you are actually sending a message to the object (which itself). The runtime tries to resolve this message and will use one of several mechanisms: if you define a method with a comparable name, this method will be used if such a method (or property) does not exist, then the default encoding key will use the same named ivar.

As for exposure, this will vary depending on your code. For example, if your property is saved (as opposed to assigned), there is a very significant difference between:

 someVar = nil 

and

 self.someVar = nil 

The synthesized setter will correctly free someVar before setting it to nil, whereas in the first example you are now leaked into memory. This is just one example of a difference.

+1
source

[self foo] calls the -foo method (not iVar, the instance method) on self .

self.bar uses the @property syntax to access the iVar bar by calling the getter / setter ( -bar and -setBar: on itself.

Recalling iVar directly without an "I". (e.g. bar = @"some text" ) bypasses the getter / setter. This could be Bad Thing if the setter (for example) should use copy or retain for the new value.

0
source

All Articles