In Objective-C what is the difference between accessing a variable in a class by using ->
(arrow operator) and .
(dot operator) ? Is ->
used to access directly vs dot (.
) isn't direct?
标签:
objective-c
相关问题
- CALayer - backgroundColor flipped?
- Core Data lightweight migration crashes after App
- back button text does not change
- iOS (objective-c) compression_decode_buffer() retu
- how to find the index position of the ARRAY Where
相关文章
- 现在使用swift开发ios应用好还是swift?
- TCC __TCCAccessRequest_block_invoke
- xcode 4 garbage collection removed?
- Unable to process app at this time due to a genera
- How can I add media attachments to my push notific
- didBeginContact:(SKPhysicsContact *)contact not in
- Custom Marker performance iOS, crash with result “
- Why is my library not able to expand on the CocoaP
When you use the arrow operator
ptr->member
it's implicitly dereferencing that pointer. It's equivalent to(*ptr).member
. When you send messages to an object pointer, the pointer is implicitly dereferenced as well.->
is the traditional C operator to access a member of a structure referenced by a pointer. Since Objective-C objects are (usually) used as pointers and an Objective-C class is a structure, you can use->
to access its members, which (usually) correspond to instance variables. Note that if you’re trying to access an instance variable from outside the class then the instance variable must be marked as public.So, for example:
accesses the instance variable
name
, declared inSomeClass
(or one of its superclasses), corresponding to the objectobj
.On the other hand,
.
is (usually) used as the dot syntax for getter and setter methods. For example:is equivalent to using the getter method
name
:If
name
is a declared property, it’s possible to give its getter method another name.The dot syntax is also used for setter methods. For example:
is equivalent to:
The arrow,
->
, is a shorthand for a dot combined with a pointer dereference, these two are the same for some pointerp
:The arrow notation is inherited from C and C has it because the structure member accessing operator (
.
) binds looser than the pointer dereferencing operator (*
) and no one wants to write(*p).m
all the time nor do they want to change the operator precedence to make people write*(p.m)
to dereference a pointer inside a structure. So, the arrow was added so that you could do bothp->m
and*s.p
sensibly without the ugliness of the parentheses.