self.var 和简单的 var 之间的区别 [英] Difference between self.var and simply var

查看:27
本文介绍了self.var 和简单的 var 之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Objective-C 类中使用 self.var 与仅使用 var 有什么区别?其中一个有好处或危险吗?

What is the difference between using self.var vs. just var in an Objective-C class? Are there benefits or dangers to one or the other?

推荐答案

foo = self.var;
self.var = foo;

在概念上与

foo = [self var];
[self setVar: foo];

所以使用点表示法,您实际上是在向自己发送消息.

So using dot notation, you are really sending messages to self.

foo = var;
var = foo;

在概念上与

foo = self->var;
self->var = foo;

因此,不使用点表示法访问实例变量与将 self 视为指向 C 结构体的指针并直接访问结构体字段相同.

So not using dot notation to access an instance variable is the same as treating self as a pointer to a C struct and accessing the struct fields directly.

在几乎所有情况下,最好使用属性(点符号或消息发送符号).这是因为可以使该属性自动执行必要的保留/复制/释放以阻止内存泄漏.此外,您可以使用 键值观察 与属性.子类还可以覆盖属性以提供自己的实现.

In almost all cases, it is preferable to use the property (either dot notation or message sending notation). This is because the property can be made to automatically do the necessary retain/copy/release to stop memory leaks. Also, you can use key value observing with a property. Also subclasses can override properties to provide their own implementation.

使用属性的两个例外是在 init 中设置 ivar 和在 dealloc 中释放它.这是因为您几乎肯定希望避免在这些方法中意外使用子类覆盖,并且您不想触发任何 KVO 通知.

The two exceptions to using properties are when setting an ivar in init and when releasing it in dealloc. This is because you almost certainly want to avoid accidentally using a sub class override in those methods and you don't want to trigger any KVO notifications.

这篇关于self.var 和简单的 var 之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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