我什么时候应该使用“self”关键字? [英] When should I use the “self” keyword?

查看:113
本文介绍了我什么时候应该使用“self”关键字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该何时在iphone开发应用程序中使用 self 表达式?说我有2个字段: UITextField * text1; NSString * str1; 保留并合成。

When should I be using the self expression in my iphone development applications? say i have 2 fields: UITextField *text1; and NSString *str1; retained and synthesized.

当我访问这两个字段中的任何一个时,我何时应该何时不使用 self.text1 self.str1

when i am accessing either of these 2 fields, when should i and when should i not use self.text1 and self.str1 ?

推荐答案

在某些情况下,它通常是不鼓励使用 self。 -expression来访问属性。 通常您 始终 使用 自我 可以访问任何属性。这是最安全,最简单的方法。特别是如果您使用了retain,那么将为您完成内存管理。

There are certain circumstances where it's generally discouraged to use the self.-expression to access a property. Normally you always use self for any access of a property. It's the most secure and uncomplicated way. Especially if you used retain, then memory management will be done for you.

此规则的两个例外:


  • 任何 init 方法。

  • dealloc

  • Any init method.
  • In dealloc.

在这两种情况下,您都在处理部分初始化的对象。在这里使用setter或getter时可能会出现一些副作用 - 因为它们是方法,因此可能会被覆盖。

In both cases you are dealing with an partially initialized object. There are some side effects that may occur when using setters or getters here -- because they are methods and hence may be overridden.

例如 ,带一个 A 的类,其属性 foo 已被类 B 。子类 B 添加一个属性 bar 并覆盖 foo 。现在你的 init -method调用 setFoo:,因为你使用了 self.foo = .. 。带有一些初始值。但是,子类还在此setter中访问 bar 的值。但在这种情况下,可能会发生bar从未被初始化并指向某些任意数据。 在init中调用setter导致崩溃,尽管在​​您自己的代码中概率可能不会太高。

For example, take a class A with a property foo that has been subclassed by class B. The subclass B adds an property bar and overrode the setter for foo. Now your init-method calls setFoo:, because you used self.foo = ... with some initial value. The subclass, however, also accesses the value of bar in this setter. But in this case, it may happen that bar has never been initialized and points at some arbitrary data. Calling a setter in init my cause crashes, although the probability may not be too high in your own code.

这篇关于我什么时候应该使用“self”关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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