What is the difference between '->' (arrow operator) and '.' (dot operator) in Objective-C?
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?
Solution 1:
->
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:
SomeClass *obj = …;
NSLog(@"name = %@", obj->name);
obj->name = @"Jim";
accesses the instance variable name
, declared in SomeClass
(or one of its superclasses), corresponding to the object obj
.
On the other hand, .
is (usually) used as the dot syntax for getter and setter methods. For example:
SomeClass *obj = …;
NSLog(@"name = %@", obj.name);
is equivalent to using the getter method name
:
SomeClass *obj = …;
NSLog(@"name = %@", [obj 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:
SomeClass *obj = …;
obj.name = @"Jim";
is equivalent to:
SomeClass *obj = …;
[obj setName:@"Jim"];
Solution 2:
The arrow, ->
, is a shorthand for a dot combined with a pointer dereference, these two are the same for some pointer p
:
p->m
(*p).m
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 both p->m
and *s.p
sensibly without the ugliness of the parentheses.