一篇Objective-C(最佳)实践的文章

2012-04-03 00:20:25 +08:00
 fly2never
http://ironwolf.dangerousgames.com/blog/archives/913
仔细读了一遍,很是赞同,特别是对团队开发,内存使用容易错误的地方规范了一下,减少内存问题出错的可能.
6497 次点击
所在节点    iDev
11 条回复
MartianZ
2012-04-03 09:14:35 +08:00
真不错,受益匪浅

感谢楼主分享
ultragtx
2012-04-11 15:44:04 +08:00
这两天按着这个改了改习惯,发现@implementation里面如果照他说的
“ALWAYS create a @property for every data member and use “self.name” to access it throughout your class implementation. NEVER access your own data members directly.”
全部用self.myobj访问来获得成员的值,单步调试Step Into的时候简直就是个悲剧 每次都要跳到@synthesize一次

赋值的时候是应该用self调用setter,但是获取变量的值的话感觉完全没有必要用self,而且一般情况下很少手写setter和getter,个别几个特殊的注意一下就行了,追求一致性也不至于到这个份上,还是直接用 _myobj 或者 myobj_ 这种方式访问比较靠谱
xesique
2012-04-11 16:25:42 +08:00
楼上的@ 含义变了,有没有转义的@ 符号啊?
试试
\@implementation
fly2never
2012-04-11 16:52:03 +08:00
@ultragtx 全部用属性而不用成员变量的原因我觉得是通过强制规范禁止使用成员变量,以免内存问题.取消了成员变量就不可能出现成员变量被赋值的情况,全部都通过属性来处理.这样对团队开发很有意义.当然如果一个人开发,能保证setter的时候全部用属性,不用成员变量也没大问题.
ultragtx
2012-04-11 21:28:22 +08:00
@fly2never 赋值取值一般人难道还分不清么 这种加self方法基本能把step into功能废掉了 如果你们团队不进行这种调试那就当我没说
fly2never
2012-04-12 13:01:06 +08:00
@ultragtx 嗯,想了下这样确实不好.class类中如果要使用,还是推荐instance variable.
原文中有描述:
"NEVER allow your instance variable names to be confused with property names, or with data member names. ALWAYS end your instance variable names with an underscore. UNLESS you are subclassing a 3rd-party class which already has a data member of the same name, in which case pick another non-similar name or add another underscore and put a comment in as to why you did this.

Use “@synthesize name = name_;” in your implementation, instead of just “@synthesize name;”

WHY?
Even within the class implementation you have to have a very good reason to access a data member directly, instead preferring property accessors."
fly2never
2012-04-12 13:03:22 +08:00
@ultragtx 这里的"NEVER access your own data members directly" 应该是指子类吧.
其他类调用,默认protect会禁止使用,只有子类才有可能直接使用.
lasse
2012-04-13 09:12:49 +08:00
fly2never
2012-05-22 18:53:22 +08:00
edison0951
2012-05-28 18:10:13 +08:00
@fly2never,那你觉得不要成员变量,全用属性来控制的缺点在哪?
gonefish
2012-05-28 18:30:00 +08:00
有很多个人习惯

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/31217

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX