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 using -> (arrow operator) and . (point operator)? Is -> for direct access to the point ( . )?

+15
objective-c
Jul 09 2018-11-11T00:
source share
3 answers

-> is the traditional C operator for accessing a member of the structure referenced by a pointer. Since Objective-C objects are usually used as pointers, and the Objective-C class is a structure, you can use -> to access its members, which (as a rule) correspond to instance variables. Please note: if you are trying to access an instance variable outside the class, then the instance variable should be marked as public.

So for example:

 SomeClass *obj = …; NSLog(@"name = %@", obj->name); obj->name = @"Jim"; 

refers to the instance variable name declared in SomeClass (or one of its superclasses) corresponding to the obj object.

On the other hand . used (usually) as dot> syntax for getter and setter methods . For example:

 SomeClass *obj = …; NSLog(@"name = %@", obj.name); 

equivalent to using the getter method name :

 SomeClass *obj = …; NSLog(@"name = %@", [obj name]); 

If name is a declared property , you can assign it to the getter method with a different name.

Dot syntax is also used for setter methods. For example:

 SomeClass *obj = …; obj.name = @"Jim"; 

equivalent to:

 SomeClass *obj = …; [obj setName:@"Jim"]; 
+18
Jul 09 '11 at 3:12
source share

The arrow, -> , is the abbreviation for the point in combination with the dereferencing of the pointer, these two are the same for some pointer p :

 p->m (*p).m 

The arrow designation inherits from C and C has it, because the access operator to the member of the structure ( . ) Is weaker than the dereference operator of the pointer ( * ), and no one wants to write (*p).m all the time and they want to change the priority of the operator so that people write *(pm) to dereference the pointer inside the structure. So, an arrow has been added so you can do both p->m and *sp intelligently without the ugliness of parentheses.

+9
Jul 09 '11 at 3:12
source share

When you use the ptr->member arrow operator, it implicitly ptr->member that pointer. This is equivalent to (*ptr).member . When you send messages to a pointer to an object, the pointer is implicitly dereferenced.

0
Jul 09 '11 at 3:12
source share



All Articles