简体   繁体   中英

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?

-> 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"];

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 *(pm) to dereference a pointer inside a structure. So, the arrow was added so that you could do both p->m and *sp sensibly without the ugliness of the parentheses.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM