开发者

iVars, With and Without self?

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 s开发者_如何转开发pecify an iVar rather than maybe some similar local variable?

@implementation ViewController
@synthesize dataForTable;

...

NSUInteger dataCount = [[self dataForTable] count];

much appreciated

Gary.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜