views:

37

answers:

2

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 that object. But if you miss self off and directly specify the iVar [dataTable count] how does that differ, what are you protecting against by using self, is it just to uniquely specify an iVar rather than maybe some similar local variable?

@implementation ViewController
@synthesize dataForTable;

...

NSUInteger dataCount = [[self dataForTable] count];

much appreciated

Gary.

+1  A: 

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.

Darryl H. Thomas
Much appreciated.
fuzzygoat
A: 

[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.

David Gelhar
I would set bar using: [self setBar:@"some text"]; as your actually "setting" something. In the example [[self dataForTable] count]; is this using a getter then, where [dataForTable count] would not be?
fuzzygoat
count is a getter on dataForTable in both cases, but in the first case, you're using a getter for dataForTable and in the second you are accessing the ivar directly.
Darryl H. Thomas
I see, thank you ...
fuzzygoat