What is the difference between '->' (arrow

2020-01-25 08:08发布

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
3条回答
你好瞎i
2楼-- · 2020-01-25 08:27

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.

查看更多
啃猪蹄的小仙女
3楼-- · 2020-01-25 08:30

-> 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"];
查看更多
家丑人穷心不美
4楼-- · 2020-01-25 08:44

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.

查看更多
登录 后发表回答