Objective-C编码规范

代码组织

在函数分组和protocol/delegate实现中使用#pragma mark -来分类方法,要遵循以下一般结构:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#pragma mark - Lifecycle

- (instancetype)init {}
- (void)dealloc {}
- (void)viewDidLoad {}
- (void)viewWillAppear:(BOOL)animated {}
- (void)didReceiveMemoryWarning {}

#pragma mark - Custom Accessors

- (void)setCustomProperty:(id)value {}
- (id)customProperty {}

#pragma mark - IBActions

- (IBAction)submitData:(id)sender {}

#pragma mark - Public

- (void)publicMethod {}

#pragma mark - Private

- (void)privateMethod {}

#pragma mark - Protocol conformance
#pragma mark - UITextFieldDelegate
#pragma mark - UITableViewDataSource
#pragma mark - UITableViewDelegate

#pragma mark - NSCopying

- (id)copyWithZone:(NSZone *)zone {}

#pragma mark - NSObject

- (NSString *)description {}

空格

  • 缩进使用4个空格,确保在Xcode偏好设置来设置。(raywenderlich.com使用2个空格)
  • 方法大括号和其他大括号(if/else/switch/while 等.)总是在同一行语句打开但在新行中关闭。

应该:

1
2
3
4
5
if (user.isHappy) {
//Do something
} else {
//Do something else
}

不应该:

1
2
3
4
5
6
7
if (user.isHappy)
{
//Do something
}
else {
//Do something else
}

应该:

1
2
3
4
5
6
// blocks are easily readable
[UIView animateWithDuration:1.0 animations:^{
// something
} completion:^(BOOL finished) {
// something
}];

不应该:

1
2
3
4
5
6
7
8
// colon-aligning makes the block indentation hard to read
[UIView animateWithDuration:1.0
animations:^{
// something
}
completion:^(BOOL finished) {
// something
}];

作者 @W_C__L
2017 年 07月 06日

简单不先于复杂,而是在复杂之后~~