变量
- 变量名称遵循驼峰命名法则
- 变量名称采用英文命名且命名所见即所得,明确变量的意义。不得存在拼音或含糊不清的英文表达
- 变量的指针位置遵循以下写法
NSString *userName; //指针需要靠近变量名而不是变量类型
- 成员变量需要加上以
m_
为前缀,如:m_userName
函数
- 函数需按照以下写法:
- (void)exampleFuntion:(NSString *)param {
//函数开始符- 与(void)之间要有一个空格
//{}首个符号不能换行且需要与参数留有一个空格
}
- 如果函数参数有多个的时候,将每个参数单独拆成一行,每个参数的冒号对齐
- (void)doSomethingWith:(NSString *)theFoo
rect:(CGRect)rect
interval:(CGFloat)interval {
...
}
- 方法调用的时候应尽量保持与方法声明的格式一致。当格式的风格有多种选择时,新的代码要与已有代码保持一致
调用时所有参数应该在同一行:
[myObject doFooWith:arg1 name:arg2 error:arg3];
或者每行一个参数,以冒号对齐:
[myObject doFooWith:arg1
name:arg2
error:arg3];
协议名
- 类型标识符和尖括号内的协议名之间,不能有任何空格
这条规则适用于类声明、实例变量以及方法声明。例如:
@interface MyProtocoledClass : NSObject<NSWindowDelegate> {
@private id<MyFancyDelegate> delegate_;
}
- (void)setDelegate:(id<MyFancyDelegate>)aDelegate;
@end
注释
- 注释采用
VVDocument
工具进行注释
nil的检查
*要注意检查判断边界
枚举
采用如下方式写枚举
typedef NS_ENUM(NSInteger, UITableViewStyle) {
UITableViewStylePlain, // regular table view
UITableViewStyleGrouped // preferences style table view
};
宏定义
- 宏定义都写在框架统一的文件里面
pragma Mark
pragma mark -
是一个在类内部组织代码并且帮助你分组方法实现的好办法。 我们建议使用 #pragma mark -
来分离:
- 不同功能组的方法
- protocols 的实现
- 对父类方法的重写
- (void)dealloc { /* ... */ }
- (instancetype)init { /* ... */ }
#pragma mark - View Lifecycle (View 的生命周期)
- (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)zoc_privateMethod { /* ... */ }
#pragma mark - UITableViewDataSource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { /* ... */ }
#pragma mark - ZOCSuperclass
// ... 重载来自 ZOCSuperclass 的方法
#pragma mark - NSObject
- (NSString *)description { /* ... */ }
self 的循环引用
当使用代码块和异步分发的时候,要注意避免引用循环。 总是使用 weak
来引用对象,避免引用循环。此外,把持有 block 的属性设置为 nil (比如self.completionBlock = nil
) 是一个好的实践。它会打破 block 捕获的作用域带来的引用循环。
**例子:**
__weak __typeof(self) weakSelf = self;
[self executeBlock:^(NSData *data, NSError *error) {
[weakSelf doSomethingWithData:data];
}];
**不要这样:**
[self executeBlock:^(NSData *data, NSError *error) {
[self doSomethingWithData:data];
}];
**多个语句的例子:**
__weak __typeof(self)weakSelf = self;
[self executeBlock:^(NSData *data, NSError *error) {
__strong __typeof(weakSelf) strongSelf = weakSelf;
if (strongSelf) {
[strongSelf doSomethingWithData:data];
[strongSelf doSomethingWithData:data];
}
}];
**不要这样:**
__weak __typeof(self)weakSelf = self;
[self executeBlock:^(NSData *data, NSError *error) {
[weakSelf doSomethingWithData:data];
[weakSelf doSomethingWithData:data];
}];
待续...