开发者

Why call "self.classVariable" when you can just call "classVariable"?

开发者 https://www.devze.com 2023-02-07 00:41 出处:网络
I understand that one version directly accesses the instance variable and the other calls it\'s accessor method.

I understand that one version directly accesses the instance variable and the other calls it's accessor method.

If self.classVariable = sandwich; 

&

If classVariable = sandwich; 

do the same thing.

Can som开发者_C百科eone explain the point of the extra typing?


In Objective-C, self.property is property access, not direct instance variable access. It is syntatic sugar for [self property] or [self setProperty:], and thus has the semantics of a message. Modern Objective-C runtime can synthesize a backing instance variable (of the same name as the property), but you may back a property with an instance variable with a different name or none at all. In other words,

self.property = foo;
id bar = property

and

property = foo;
id bar = property;

are not at all the same thing.

It's generally a bad idea to mix direct and property access (with the exception that you should be accessing ivars directly in -init and -dealloc methods) because you will easily run afoul of memory management rules.


The extra typing is to protect the code from future changes, in case a variable is named (in scope) equal to the class member.

It is also considered good practice (in some circles) to include Self when referring to members in the class to be unambiguously clear where it comes from which in some ways helps quicken comprehension of the code.

For Objective-C specifically, there is another difference as noted here http://answers.oreilly.com/topic/1193-calling-self-object-rather-than-calling-the-object-directly-in-objective-c/

The SELF.X notation goes through the accessors generated by the @synthesize directive, whereas X directly bypasses them.


If you go through the accessor you can set breakpoints there. Handy sometimes. Also things like retain/copy properties won't work if you don't go through the accessor.

0

精彩评论

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