iOS
OC代码规范
命名
Preferred :UIColor *myColor = [UIColor whiteColor];
Not Preferred :
UIColor *myColour = [UIColor whiteColor];
代码组织
使用#pragma mark - 将生命周期、分类方法和代理方法分块标注管理#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 {}
#pragma mark - lazy
空格
- 使用2个空格不要使用Tab键
- 方法和其他后的大括弧在第一行开始在新的一行结束。 Preferred:
if (user.isHappy) {
//Do something
} else {
//Do something else
}
Not Preferred:
if (user.isHappy)
{
//Do something
}
else {
//Do something else
}
- 在方法中的参数中间添加一个空格方便阅读。
- 优先使用自动生成,但是如果需要的话可以在实现文件中添加@ synthesize 和 @dynamic。
- 调用方法时尽量避免方法中冒号对齐。当方法中包含3个以上的参数,使用冒号对齐会增加方法的可读性。但是,当方法中包含block时Xcode 的自动对齐会让代码看起来不容易分辨。 Preferred:
// blocks are easily readable
[UIView animateWithDuration:1.0 animations:^{
// something
} completion:^(BOOL finished) {
// something
}];
Not Preferred:
// colon-aligning makes the block indentation hard to read
[UIView animateWithDuration:1.0
animations:^{
// something
}
completion:^(BOOL finished) {
// something
}];
(更多…)