iPhone - difference between these two lines of code
What is the diffrence between these two lines of code:
开发者_JAVA百科[cmController currentPageNo];
self.cmController.currentPageNo;
There is actually a functional difference - the second line is equivalent to:
[[self cmController] currentPageNo];
Using the -cmController
property getter method to access the cmController
ivar may have behaviours that make it different to accessing the ivar directly. These might include lazy initialisation or atomic thread locking, or a range of other behaviours. Unless you have a good reason to, you should (in general) use the accessor methods for properties, rather than accessing ivars directly.
So to clarify:
[cmController currentPageNo]; // 1
cmController.currentPageNo; // 2
[[self cmController] currentPageNo]; // 3
self.cmController.currentPageNo; // 4
1 and 2 are functionally identical to each other, but use different syntax. 3 and 4 are also functionally identical to each other, but use different syntax. You should use version 4, or version 3 if you have an aversion to dot-syntax.
Generally, dot notation is just syntactical sugar.
But in this case, there actually is some difference.
[cmController currentPageNo];
This will use the class's instance variable directly to get your cmController. It will then send the currentPageNo to it.
self.cmController.currentPageNo;
This, on the other hand, will use the current class's property definition to get the cmController via the class's ivar.
This means, basically, the the first is slightly more efficient than the second. Not because you used dot notation, but because you used cmController directly instead of self.cmController
. [whatever currentPageNo]
is the same as whatever.currentPageNo
.
These lines are equivalent except for the syntax used:
[cmController currentPageNo];
cmController.currentPageNo;
On the other hand, these lines are equivalent except for the syntax used:
self.cmController.currentPageNo;
[[self cmController] currentPageNo];
I hope that's clear.
You can read about dot notation here.
There's no difference, functionally; objective C 2.0 just introduced the dot notation, giving those who aren't as into the brackets a way out.
EDIT:
As the comments pointed out, of course this is wrong. I was responding to the (unasked) question of "what's the difference between [cmController currentPageNo];
and self.cmController.currentPageNo;
?"
Nick's answer gives the true answer, which is that the first line directly accesses the variable, while the second line uses the variable's getter method. The two lines also differ in that the first uses typical bracket notation, while the second does indeed use the new dot notation from objective C 2.0.
精彩评论