我为什么要使用@properties?

编程入门 行业动态 更新时间:2024-10-28 18:32:15
本文介绍了我为什么要使用@properties?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

可能重复: 什么描述@property(…)最好?什么是真正有用的?

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

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

如果我使用 @property(保留)Something * myVar; 我可以用 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?

本文发布于:2023-06-08 03:00:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/572868.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:我为   要使   properties

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!