iVars, With and Without self?

前端 未结 2 1467
猫巷女王i
猫巷女王i 2021-01-27 22:45

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

2条回答
  •  南方客
    南方客 (楼主)
    2021-01-27 22:56

    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.

提交回复
热议问题