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

查看:127
本文介绍了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;

因此,不使用点表示法访问实例变量与将自我视为指向C结构并直接访问struct字段。

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天全站免登陆