[英]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 .
在 Objective-C 中,使用->
(箭头运算符)和访问 class 中的变量有什么区别.
(dot operator)? (点运算符)? Is ->
used to access directly vs dot ( .
) isn't direct?是->
用于直接访问 vs 点( .
)不是直接的吗?
->
is the traditional C operator to access a member of a structure referenced by a pointer. ->
是传统的 C 运算符,用于访问指针引用的结构的成员。 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.由于 Objective-C 对象(通常)用作指针和 Objective-C class 是一个结构,您可以使用->
访问其成员,这(通常)对应于实例变量Note that if you're trying to access an instance variable from outside the class then the instance variable must be marked as public.请注意,如果您尝试从 class 外部访问实例变量,则必须将实例变量标记为公共。
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
.访问在SomeClass
(或其超类之一)中声明的实例变量name
,对应于 object obj
。
On the other hand, .
另一方面, .
is (usually) used as the dot syntax for getter and setter methods. (通常)用作 getter 和 setter方法的点语法。 For example:例如:
SomeClass *obj = …;
NSLog(@"name = %@", obj.name);
is equivalent to using the getter method name
:等效于使用 getter 方法name
:
SomeClass *obj = …;
NSLog(@"name = %@", [obj name]);
If name
is a declared property , it's possible to give its getter method another name.如果name
是已声明的属性,则可以为其 getter 方法指定另一个名称。
The dot syntax is also used for setter methods.点语法也用于 setter 方法。 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
是相同的:
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.箭头符号是从 C 和 C 继承的,因为结构成员访问运算符 ( .
) 绑定比指针解引用运算符 ( *
) 更松散,没有人想一直写(*p).m
也不想写更改运算符优先级以使人们编写*(pm)
以取消引用结构内的指针。 So, the arrow was added so that you could do both p->m
and *sp
sensibly without the ugliness of the parentheses.因此,添加了箭头,这样您就可以明智地执行p->m
和*sp
而不会出现括号的丑陋。
When you use the arrow operator ptr->member
it's implicitly dereferencing that pointer.当您使用箭头运算符ptr->member
时,它会隐式取消引用该指针。 It's equivalent to (*ptr).member
.它相当于(*ptr).member
。 When you send messages to an object pointer, the pointer is implicitly dereferenced as well.当您向 object 指针发送消息时,该指针也被隐式取消引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.