目标C - 使用属性获取访问器vs直接使用iVar [英] Objective C - Using property get accessor vs directly using iVar

查看:101
本文介绍了目标C - 使用属性获取访问器vs直接使用iVar的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道使用(get)访问器读取属性的值和直接使用iVar之间的区别是什么?

I was wondering what exactly are the differences between using the (get) accessor for reading the value of property and directly using the iVar?

说我有一个类它声明一个属性:

Say I have a class which declares a property:

@interface Foo : NSObject

@property (strong) NSString *someString;

@end

在实现中我使用它。以下两行之间有什么区别:

And in the implementation I'm using it. Are there any differences between the following two lines:

someLabel.text = self.someString;

someLabel.text = _someString;

对于设置访问器很清楚。 Afaik对于强属性,访问器负责保留和释放(一个有趣的'侧面问题'将是如果ARC更改,即直接设置iVar [假设它不是一个__weak iVar]也使用ARC保留和释放)

For set accessors it's clear. Afaik for strong properties the accessor takes care of retain and release (an interesting 'side question' would be if ARC changes that, i.e. does setting the iVar directly [assuming it's not an __weak iVar] also retain and release correctly using ARC), also KVO requires the use of accessors to work properly etc. But what about getters?

如果没有差别,有没有一种方式被认为是最佳实践?

And if there's no difference, is there one way considered best practice?

Thx

推荐答案

如你所知,调用 self.someString 真的 [self someString] 。如果你选择创建一个属性,那么你应该使用该属性。可能有其他语义添加到属性。也许该属性是懒加载。也许该属性不使用ivar。也许有一些其他需要的副作用调用属性的getter。也许现在没有,但也许这种变化在未来。调用该属性现在可以让您的代码有更多的未来证明。

As you know, calling self.someString is really [self someString]. If you chose to create a property then you should use the property. There may be other semantics added to the property. Perhaps the property is lazy loaded. Perhaps the property doesn't use an ivar. Perhaps there is some other needed side effect to calling the property's getter. Maybe there isn't now but maybe this changes in the future. Calling the property now makes your code a little more future proof.

如果你有一个ivar和一个属性,使用该属性,除非你有明确的理由使用ivar 。可能有一种情况,你不想要执行任何额外的语义或副作用的属性。所以在这种情况下,直接使用ivar是更好的。

If you have an ivar and a property, use the property unless you have explicit reason to use the ivar instead. There may be a case where you don't want any of the extra semantics or side effect of the property to be performed. So in such a case, using the ivar directly is better.

但最终,它是你的代码,你的属性,你的ivar。你知道为什么你添加了一个属性。您知道该资源的任何潜在收益(如果有)。

But ultimately, it's your code, your property, your ivar. You know why you added a property. You know any potential benefits of that property, if any.

这篇关于目标C - 使用属性获取访问器vs直接使用iVar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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