Daniel's Objective-C Coding Style GuidelinesFrom:杨德升 /http://desheng.me/ desheng.young@gmail.com
Date: 2010.10.31
参考资料:
• Apple: Coding Guidelines for Cocoa
• Google: Objective-C Style Guide
• Three20: Source code style guildelines
正文:
• 格式化代码
◦ 指针“*”号的位置
▪ 如:NSString*varName;
◦ 空格VS tabs
▪ 只允许使用空格,将编辑器设置为1个TAB= 2个字符缩进
◦ 每行的长度
-
▪ 每行最多不得超过100个字符
-
▪ 以15寸MacbookPro的大小,每行100个字符时能最大化地同时容下编辑器和iPhone模拟器
-
▪ Google的80字符的标准有点少,这导致过于频繁的换行(Objectve-C的代码一般都很长)
-
▪ 通过“Xcode => Preferences => TextEditing =>勾选Show Page Guide /输入
100 => OK” 来设置提醒◦方法的声明和定义
-
▪ 在- OR + 和返回值之间留1个空格,方法名和第一个参数间不留空格。如:- (void)doSomethingWithString:(NSString *)theString {
...}
-
▪ 当参数过长时,每个参数占用一行,以冒号对齐。如:- (void)doSomethingWith:(GTMFoo *)theFoo
rect:(NSRect)theRect interval:(float)theInterval {
...}
-
▪ 如果方法名比参数名短,每个参数占用一行,至少缩进4个字符,且为垂直对齐(而非使用冒号对齐)。如:
- (void)short:(GTMFoo *)theFoolongKeyword:(NSRect)theRect
evenLongerKeyword:(float)theInterval { ...
}
◦ 方法的调用
-
▪ 调用方法沿用声明方法的习惯。例外:如果给定源文件已经遵从某种习惯,继续遵从那种习惯。
-
▪ 所有参数应在同一行中,或者每个参数占用一行且使用冒号对齐。如:
[myObject doFooWith:arg1 name:arg2 error:arg3];
或
[myObject doFooWith:arg1 name:arg2
error:arg3];
-
▪ 和方法的声明一样,如果无法使用冒号对齐时,每个参数一行、缩进4个字符、垂直对其(而非使用冒号对齐)。如:
[myObj short:arg1longKeyword:arg2
evenLongerKeyword:arg3];
◦ @public和 @private
▪ @public和 @private使用单独一行,且缩进1个字符
◦Protocals
-
▪ 类型标示符、代理名称、尖括号间不留空格。
-
▪ 该规则同样适用于:类声明、实例变量和方法声明。如:
@interface MyProtocoledClass : NSObject<NSWindowDelegate> { @private
id<MyFancyDelegate> _delegate; }
- (void)setDelegate:(id<MyFancyDelegate>)aDelegate;
@end
-
▪ 如果类声明中包含多个protocal,每个protocal占用一行,缩进2个字符。如:@interface CustomViewController : ViewController<
AbcDelegate,
DefDelegate>{
...}
其他规范见下:
-