我为什么要使用@properties? [英] Why should I use @properties?

查看:85
本文介绍了我为什么要使用@properties?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

什么描述@property(…)最好?什么是真正有用的?

如果我在类接口中声明一个变量,我可以在我班上的任何地方使用这样的变量。真棒。

If I declare a variable in my class interface, I can use such variable anywhere on my class. Awesome.

如果我使用 @property(保留)Something * myVar; 我可以用<$访问该变量c $ c> self.myVar ......但是,有什么区别?我应该使用一种方法还是另一种方法?

If I use @property (retain) Something *myVar; I can access that variable with self.myVar... But, what is the difference? Is there a good reason I should use one method or another?

推荐答案

简答:内存管理的封装。

Short answer: Encapsulation of memory management.

更长的答案:如果您想稍后使用它,您需要建立对象的所有权。如果你想在以后使用它,你需要使用它来引用它,并且保持该引用的一个好地方是在一个实例变量中。

Longer answer: You need to establish ownership of an object if you want to use it later. If you want to use it later, you'll need a reference to it with which to do so, and a great place to keep that reference is in an instance variable.

每次为此分配新值时,都可以处理所有权声明(即保留和释放),但这样会在整个地方散布大量重复且容易出错的样板代码,喜欢水果蛋糕中的樱桃。当(不是)出现问题时,这种混乱很难调试。因此,最好将这些代码包装在访问器方法中,这样你就可以编写一次然后忘掉它。

You could handle the ownership claims (i.e. retains and releases) each time you assign a new value to that, but that would leave a lot of repetitious and trouble-prone boilerplate code scattered all over the place, like cherries in a fruitcake. That kind of mess is fiendishly difficult to debug when (not if) something goes wrong. So, it's far better to wrap that code up in accessor methods, so you can write it once and then forget about it.

但是访问器方法也大多是样板文件,所以我们使用@property声明自动创建它们,而不是手工编写它们。

But accessor methods are mostly boilerplate too, so we use @property declarations to create them automagically, rather than writing them by hand.

编辑:Apple的内存管理指南提供了很多的详细信息@property生成的访问器方法在幕后做什么。

Edit: Apple's Memory Management Guide provides a lot of detail about what the accessor methods generated by @property do behind the scenes.

这篇关于我为什么要使用@properties?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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