I am just curious about the role that self plays within an object. I understand that writing [[self dataForTable] count]
refers directly to the iVar contained in th
[self foo]
invokes the -foo
method (not iVar, instance method) on self
.
self.bar
uses @property syntax to access the bar
iVar, by calling the getter/setter methods (-bar
and -setBar:
) on self.
Referring to the iVar directly without "self." (e.g. bar = @"some text"
) bypasses the getter/setter. That can be a Bad Thing if the setter is (for example) supposed to be doing a copy
or retain
on the new value.
Writing [[self dataForTable] count] does not refer directly to the iVar. There's some behind-the-scenes stuff going on...
If you use an ivar in your code without self, that's direct access to the ivar. If you use either [self someIvarName] or self.someIvarName, you're actually sending a message to the object (which is self). The runtime attempts to resolve this message and will use one of a number of mechanisms: If you have defined a method with a matching name, that method will be used, if no such method (or property) exists, then key-value-coding will use an identically named ivar by default.
As for the impact, this will differ based on your code. For example if your property is a retained property (as opposed to assigned), there's a very significant difference between:
someVar = nil
and
self.someVar = nil
The synthesized setter will properly release someVar before setting it to nil, whereas in the first example, you've now leaked memory. This is just one example of the difference.