'->和有什么区别(箭头运算符)和“." (点运算符)在Objective-C中? [英] What is the difference between '->' (arrow operator) and '.' (dot operator) in Objective-C?

查看:103
本文介绍了'->和有什么区别(箭头运算符)和“." (点运算符)在Objective-C中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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?

推荐答案

->是传统的C运算符,用于访问指针引用的结构的成员.由于Objective-C对象通常用作指针,而Objective-C类是结构,因此可以使用->访问其成员(通常)与实例变量相对应.请注意,如果您尝试从类外部访问实例变量,则必须将实例变量标记为public.

-> 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.

例如,

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

访问在对象obj中声明的在SomeClass(或其超类之一)中声明的实例变量name.

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);

等同于使用吸气剂方法name:

is equivalent to using the getter method name:

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

如果name声明的属性 ,则可以给它的getter方法起另一个名字.

If name is a declared property, it’s possible to give its getter method another name.

点语法也用于setter方法.例如:

The dot syntax is also used for setter methods. For example:

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

等效于:

SomeClass *obj = …;
[obj setName:@"Jim"];

这篇关于'->和有什么区别(箭头运算符)和“." (点运算符)在Objective-C中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆