Skip to content

Commit 7c4bba7

Browse files
committed
格式
1 parent 511451c commit 7c4bba7

File tree

1 file changed

+104
-0
lines changed

1 file changed

+104
-0
lines changed

README.md

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,11 @@
5757
#### 清晰
5858
尽可能遵守 Apple 的命名约定,命名应该尽可能的清晰和简洁,但在Objective-C中,清晰比简洁更重要。由于Xcode强大的自动补全功能,我们不必担心名称过长的问题。
5959

60+
- 类名采用大驼峰(UpperCamelCase)
61+
- 类成员、方法小驼峰(lowerCamelCase)
62+
- 局部变量大小写首选小驼峰,也可使用小写下划线的形式(snake_case)
63+
- C函数的命名用大驼峰
64+
6065
```
6166
//清晰
6267
insertObject:atIndex:
@@ -74,6 +79,12 @@ remove:
7479

7580

7681
```
82+
// OK
83+
ID, URL, JSON, WWW
84+
85+
// 糟糕
86+
id, Url, json, www
87+
7788
//清晰
7889
destinationSelection
7990
setBackgroundColor:
@@ -549,6 +560,47 @@ NSColorPanelColorDidChangeNotification
549560

550561
同样的,在`Xcode > Preferences > Text Editing > Page guide at column:`中将最大行长设置为**80**,过长的一行代码将会导致可读性问题。
551562

563+
### 空格
564+
565+
类方法声明在方法类型与返回类型之间要有空格。
566+
567+
```
568+
// 糟糕
569+
-(void)methodName:(NSString *)string;
570+
571+
// OK
572+
- (void)methodName:(NSString *)string;
573+
```
574+
575+
条件判断的括号内侧不应有空格。
576+
577+
578+
```
579+
// 糟糕
580+
if ( a < b ) {
581+
// something
582+
}
583+
584+
// OK
585+
if (a < b) {
586+
// something
587+
}
588+
```
589+
590+
关系运算符(如 >=、!=)和逻辑运算符(如 &&、||)两边要有空格。
591+
592+
593+
```
594+
// OK
595+
(someValue > 100)? YES : NO
596+
597+
// OK
598+
(items)?: @[]
599+
```
600+
601+
二元算数运算符两侧是否加空格不确定,根据情况自己定。一元运算符与操作数之前没有空格。
602+
603+
552604
###函数的书写
553605

554606
一个典型的Objective-C函数应该是这样的:
@@ -778,6 +830,58 @@ NSDictionary *stillWrong = @{
778830
};
779831
```
780832

833+
###代码组织
834+
- 函数长度(行数)不应超过2/3屏幕,禁止超过70行。 : 例外:对于顺序执行的初始化函数,如果其中的过程没有提取为独立方法的必要,则不必限制长度。
835+
- 单个文件方法数不应超过30个
836+
- 不要按类别排序(如把IBAction放在一块),应按任务把相关的组合在一起
837+
- 禁止出现超过两层循环的代码,用函数或block替代。
838+
尽早返回错误:
839+
840+
841+
```
842+
// 为了简化示例,没有错误处理,并使用了伪代码
843+
844+
// 糟糕的例子
845+
- (Task *)creatTaskWithPath:(NSString *)path {
846+
Task *aTask;
847+
if ([path isURL]) {
848+
if ([fileManager isWritableFileAtPath:path]) {
849+
if (![taskManager hasTaskWithPath:path]) {
850+
aTask = [[Task alloc] initWithPath:path];
851+
}
852+
else {
853+
return nil;
854+
}
855+
}
856+
else {
857+
return nil;
858+
}
859+
}
860+
else {
861+
return nil;
862+
}
863+
return aTask;
864+
}
865+
866+
// 改写的例子
867+
- (Task *)creatTaskWithPath:(NSString *)path {
868+
if (![path isURL]) {
869+
return nil;
870+
}
871+
872+
if (![fileManager isWritableFileAtPath:path]) {
873+
return nil;
874+
}
875+
876+
if ([taskManager hasTaskWithPath:path]) {
877+
return nil;
878+
}
879+
880+
Task *aTask = [[Task alloc] initWithPath:path];
881+
return aTask;
882+
}
883+
```
884+
781885

782886
##编码风格
783887

0 commit comments

Comments
 (0)