“自我”在目标C中
可能的重复:
我应该在实现中使用 self 关键字(属性)吗?
假设我有一个“Person”类,带有一个实例变量“age”。来自Python,在为Person类编写方法时,我习惯于使用“self.age”访问年龄,但是在Objective CI中注意到,在引用实例时,“self.age”和“age”都被接受变量(而在 Python 中只有前者才有效)。
当没有明确指定您指的是哪个实例的变量时,它是否默认为“self”?不明确指定 self 是否被认为是不好的风格?如果没有,是否有关于何时使用 self.age 以及何时使用age 的约定?
Possible Duplicate:
Should I Use self Keyword (Properties) In The Implementation?
Say I have a class "Person", with an instance variable "age". Coming from Python, when writing methods for the Person class, I am used to accessing age using "self.age", however in Objective C I have noticed that both and "self.age" and "age" are accepted when referring to the instance variable (whereas in Python only the former would work).
When it is not explicitly specified which instance's variable you mean, does it default to 'self'? And is it considered bad style not to explicitly specify self? If not, are there conventions on when to use self.age and when to use age?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
age
和self.age
是两个完全不同的东西。在实例方法内部,对象的实例变量在作用域中隐式定义,除非被局部变量遮蔽(请参阅 Objective-C 编程语言)。这就是age
正常工作的原因。使用点表示法时,您引用的是 property,这意味着您实际上正在调用[self Age]
而不是直接访问实例变量。您还可以使用结构指针运算符 (->
) 直接访问实例变量。这很少使用,但可以用来直接访问同一类或不同类的其他实例中的变量,以及 self.因此,age
和self->age
是完全相同的东西,但self.age
却完全不同。age
andself.age
are two completely different things. Inside of instance methods, the object's instance variables are implicitly defined in the scope, unless shadowed by a local variable (See The Objective-C Programming Language). That is whyage
works correctly. When using the dot notation, you are referencing a property, which means you are actually calling[self age]
instead of directly accessing the instance variable. You can also access an instance variable directly by using the structure pointer operator (->
). This is rarely used, but can be used to directly access variables in other instances of the same class or different classes, as well as self. Therefore,age
andself->age
are exactly the same thing, butself.age
is completely different.使用 self 使用访问器和修改器方法,而省略它则直接修改实例变量。为了使用
self.age
,您必须使用@property
语法将age
声明为属性。我通常会尽可能地尝试使用self
。Using
self
uses the accessor and mutator methods, while leaving it out modifies the instance variable directly. In order to useself.age
, you must haveage
declared as a property with the@property
syntax. I typically try to useself
wherever I can.