iPhone ivar命名约定 [英] iPhone ivar naming convention

查看:89
本文介绍了iPhone ivar命名约定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

我注意到在很多参考资料中,我看到了很多当时,变量在.h文件中命名为_variable,然后在.m文件中@yntize'd为

I've noticed that in a lot of the reference materials out there, I see that a lot of the time, variables are named _variable in the .h file, then are @synthesize'd in the .m file as

@synthesize variable = _variable;

为什么要这样做?我错过了什么?

Why is this done? What am I missing?

谢谢!

推荐答案

没有就此达成共识。有些人喜欢使用它来清楚地分离出类变量,并且另一个响应者注意到避免与传入的参数名冲突。即使在Apple示例代码中,使用情况也是喜忧参半。

There is not consensus on this. Some people like to use it for clarity to separate out class variables, and as another responder noted to avoid conflict with incoming parameter names. Even in Apple sample code the use is mixed.

但是,我更倾向于不使用 _ 前缀和有两个有力的理由:

However, I greatly prefer to not use the _ prefix and have two strong reasons:

1)有些人认为 _ 是私人的一个很好的指标。我的看法是应该在没有setter / getter(属性)的情况下访问NO类局部变量,因此它们都是私有的 - 假设为什么不以更容易阅读和使用自动完成的方式命名它们?编译器可以快速显示参数名称的任何重叠,并通过更周密的参数命名(或内部变量)来避免。

1) Some people think the _ is a good indicator of "private". My take is that NO class local variable should be accessed without a setter/getter (property) and thus they are ALL private - given that why not name them in a way easier to read and use autocomplete on? Any overlap in names from parameters is quickly revealed by the compiler, and avoided through more thoughtful naming of parameters (or internal variables).

2)(更好的理由) - 如果在XCode中对内部类var使用refactor,该类名称与用于访问它的属性相同,则还将重命名property和synthesize语句。如果对前缀为 _ 的类变量使用重构,则不会更改属性名称 - 只是合成映射到内部名称。我几乎从不希望名称从属性变化到它公开访问的实际变量。仅这一点使我永远不想使用 _ 作为变量前缀,因为能够移动名称只是提高代码清晰度所能做的最有用的事情。

2) (even better reason) - if you use "refactor" in XCode on an internal class var that is named the same as the property used to access it, the property and synthesize statement will also be renamed. If you use refactor on a class variable prefixed with an _, the property name will not be changed - just the synthesize mapping to the internal name. I pretty much never want the name to vary from the property to the real variable it exposes access to. That alone makes me never want to use _ as a variable prefix, since being able to shift names is just about the most useful thing you can do to improve code clarity.

这篇关于iPhone ivar命名约定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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