代碼不僅是可以編譯的,同時應該是 “有效” 的。好的代碼有一些特性:簡明,自我解釋,優秀的組織,良好的文檔,良好的命名,優秀的設計以及可以被久經考驗。 ——《禪與 Objective-C 編程藝術》
依據日常個人和團隊編碼習慣總結、挑選出幾點Objective-C代碼規范,整理出此文,持續更新。
多條規范和思路參考《禪與 Objective-C 編程藝術》一書,非常推薦一讀。
命名規范
駝峰命名
- 屬性、變量、方法(iOS中的方法,規范的名稱應該是:消息)均使用小寫字母開頭的駝峰命名。
- 全局變量命名,以小寫字母g開頭。
static CSDataManager *gDataManager = nil; // good
static CSDataManager *dataManager = nil; // avoid
前綴
- 類名、協議名、枚舉類型、宏統一以項目前綴開頭,項目前綴為2-3個大寫字母,例如本文檔以CS(CodeStyle縮寫)作為項目前綴。
@interface OCBaseViewController : UIViewController
@end
- 避免使用以“_”開頭的實例變量,直接使用屬性替代實例變量。
@interface ViewController () {
BOOL _hasViewed; // avoid
}
@property (nonatomic, assign) BOOL isToday; // good
@end
- 私有方法也不能以“_”開頭,因為這是C++標準,且“_”前綴是Apple保留的,不要冒重載蘋果的私有方法的險。
可借助#pragma在代碼塊中區分私有方法。
- (void)_privateMethod { // avoid
}
#pragma mark - Private Method
- (void)privateMethod { // good
}
- 執行性的方法以動詞開頭,返回性的方法以返回內容開頭,但之前不要加get
- (void)replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject; // 執行性,good
+ (id)arrayWithArray:(NSArray *)array; // 返回性,good
+ (id)getArrayWithArray:(NSArray *)array; // 返回性,avoid
代碼格式
空格
- 指針"*"號的位置在變量名前,而非變量類型之后,與變量名無空格相連,與類型間有個空格:
@property (nonatomic, strong) NSString* name; // avoid
@property (nonatomic, strong) NSString *password; // good
- "{"和"("前均需要一個空格,“}”后如果緊跟著內容比如else,也需要一個空格,但“(”和“[”右邊,“)”和“]”左邊不能有空格。涉及位置:if-else,while,方法聲明和實現,@interface等。
-(void)viewDidLoad{ // avoid
[super viewDidLoad];
if([self isOk]){ // avoid
// ...
}else{ // avoid
// ...
}
}
- (void)viewDidLoad { // good
[super viewDidLoad];
if ([self isOk]) { // good
// ...
} else { // good
// ...
}
}
- 除了++和--外的運算符前后均需要一個空格。
if ( i>10 ) { // avoid
i ++; // avoid
} else {
i+=2; // avoid
}
// good
if (i > 10) {
i++;
} else {
i += 2;
}
- “,”左邊不留空格,右邊空一格
@property (nonatomic,readonly ,strong) NSString* name; // avoid
NSArray *array = @[@"A" , @"B" ,@"C"]; // avoid
@property (nonatomic, readonly, strong) NSString* name; // good
NSArray *array = @[@"A", @"B", @"C"]; // good
括號
- if、else后面必須緊跟"{ }",即便只有一行代碼。
防止之后增添邏輯時忽略增加{},邏輯代碼跑到if、else之外,同時更便于閱讀。
if (i > 10) // avoid
i++;
else
i--;
if (i > 10) { // good
i++;
} else {
i--;
}
- if-else中,else不另起一行,與if的反括號在同一行,如上段代碼所示,注意else前后均有空格。
- 花括號統一采用不換行風格。
涉及位置:@interface、方法實現、if-else、switch-case等。
優點: 減少代碼冗余行數,代碼更加緊湊,結構清晰。
// avoid
- (void)test
{
if ([self isOK])
{
// ...
}
else
{
// ...
}
}
// good
- (void)test {
if ([self isOK]) {
// ...
} else {
// ...
}
}
- switch-case中,case后的代碼多余一行,則需要{}包裹,建議所有case和default后的代碼塊均用{}包裹。
屬性
- 直接使用@property來替代實例變量,非特殊情況不使用 @synthesize 和 @dynamic
- @property括號內的描述性修飾符,嚴格按以下順序書寫:原子性,讀寫,內存管理。
因為三種描述符經常需要修改,屬性與屬性間差異比較大的是內存管理,其次才是讀寫和原子性,方便從右往左修改,也能讓代碼前部分較美觀地對齊。
// avoid
@property (copy, nonatomic, readonly) NSString *name;
@property (nonatomic, assign, readonly) NSInteger age;
@property (readwrite, strong, nonatomic) CSCard *card;
// good
@property (nonatomic, readonly, copy) NSString *name;
@property (nonatomic, readonly, assign) NSInteger age;
@property (nonatomic, readwrite, strong) CSCard *card;
- 不可變類型,但可被可變類型(Mutable)對象賦值的屬性,例如:NSString、NSArray、NSDictionary、NSURLRequest,其內存管理屬性類型必須為copy。
以防止聲明的不可變的屬性,實際賦值的是一個可變對象,對象內容還在不知情的情況下被外部修改。
@property (nonatomic, copy) NSString *name; // good
NSMutableString * name = [[NSMutableString alloc] initWithString:@"User1"];
CSUserModel *user = [CSUserModel new];
user.name = name;
[name appendString:@"0"];
NSLog(@"%@", user.name); // output:User1
@property (nonatomic, strong) NSString *name; // avoid
NSMutableString * name = [[NSMutableString alloc] initWithString:@"User1"];
CSUserModel *user = [CSUserModel new];
user.name = name;
[name appendString:@"0"];
NSLog(@"%@", user.name); // output:User10, Something Wrong!
- 避免在類的頭文件中暴露可變對象,建議提供readonly內存管理和使用不可變對象,以防止外部調用者改變內部表示,破壞封裝性。
- 避免在init和dealloc中使用點語法訪問屬性,這兩個地方需要直接訪問”_”開頭的實例變量。
因為init中訪問setter或getter,可能訪問到的是子類重寫后的方法,而方法內使用了其它未初始化或不穩定的屬性或訪問了其它方法,導致期望之外的情況發生。注:僅當init返回后,才標識著一個對象完成初始化可使用。
在dealloc方法中,對象處于釋放前不穩定狀態,訪問setter、getter可能出現問題。 - 屬性建議采用點語法訪問,以和方法調用區分開來。但是對于重寫了setter、getter的屬性,可以方法調用方式訪問,以告訴代碼閱讀者訪問的該setter、getter是重寫過,可能帶有副作用的。
其它語法
- if語句在比較時,括號內不使用nil、NO或YES
if (obj == nil && finish == YES && result == NO){ // avoid
}
if(!obj && finish && !result){ // good
}
- 盡量減少@throw、@try、@catch、@finally的使用,會影響性能
- 使用常量替代代碼中固定的字符串和數字,以方便理解、查找和替換。常量建議使用static聲明為靜態常量,除非有特殊作用才考慮使用#define
換行
- 避免使用兩行以上的空行,建議#import、@interface、@implementation、方法與方法之間以兩行空行作為間隔。
- 方法內可使用一行空行來分離不同功能的代碼塊,但通常不同功能代碼塊應該考慮抽取新的方法。
- 包含3個及以上參數的方法簽名,建議對每個參數進行換行,參數按照冒號對其,讓代碼具有更好可讀性,也便于修改。
// avoid
+ (void)animateWithDuration:(NSTimeInterval)duration animations:(void (^)(void))animations completion:(void (^)(BOOL finished))completion {
// ...
}
// good
+ (void)animateWithDuration:(NSTimeInterval)duration
animations:(void (^)(void))animations
completion:(void (^)(BOOL finished))completion {
// ...
}
注釋
- 單行注釋,“//”之后空一格,再寫具體注釋內容,如果“//”注釋與代碼在同一行,則代碼最后一個字符空一格,再寫注釋
// avoid
- (void)test {
//Just For Debug
BOOL isTest = YES;//Main Logic
//...
}
// good
- (void)test {
// Just For Debug
BOOL isTest = YES; // Main Logic
// ...
}
- 對方法簽名使用多行注釋,按照Xocde風格“Editor-Structure-Add Document”添加。Description部分,第一行用最簡單語句描述方法作用,如需詳細說明,則空一行后,再進行詳細描述。
/**
執行xxx操作,可能失敗。
xxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxx(具體使用事項)
@param error NSError,-1:xxx;-2:xxxxx
*/
- (void)methodWithError:(NSError **)error {
// ...
}
代碼組織
#pragma
- 對一個文件中的代碼使用“#pragma mark - CodeBlockName”進行分段,易于代碼維護和閱讀。
常見的區分依據和格式如下:
- (void)dealloc { /* ... */ }
- (instancetype)init { /* ... */ }
#pragma mark - View Lifecycle
- (void)viewDidLoad { /* ... */ }
- (void)didReceiveMemoryWarning { /* ... */ }
#pragma mark - Setter Getter
- (void)setCustomProperty:(id)value { /* ... */ }
- (id)customProperty { /* ... */ }
#pragma mark - IBActions
- (IBAction)onOkButtonClick:(id)sender { /* ... */ }
#pragma mark - Public
- (void)publicMethod { /* ... */ }
#pragma mark - Private
- (void)privateMethod { /* ... */ }
#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { /* ... */ }
#pragma mark - Superclass
- (void)superClassMethod { /* ... */ }
#pragma mark - NSObject
- (NSString *)description { /* ... */ }
- @interface聲明實現的協議時,一條協議占用一行,@interface所在行不書寫協議名。以便于閱讀和修改。
// avoid
@interface CodeStyleViewController () <UITableViewDelegate, UITableViewDataSource, UIActionSheetDelegate>
@end
// good
@interface CSViewController () <
UITableViewDelegate,
UITableViewDataSource,
UIActionSheetDelegate
>
@end
- dealloc方法的實現,需要放在文件最前面,一般在@implementation之后,在init或viewDidLoad之前,以便于檢查。
- 當主邏輯代碼的執行,需要滿足多個條件時,避免if語句嵌套,此時使用return語句可減少if嵌套降低循環復雜度,將條件和主邏輯清楚地區分開。
// avoid
- (void)method {
if ([self conditionA]) {
// some code..
if ([self conditionB]) {
// main logic...
}
}
}
// good
- (void)methodB {
if (![self conditionA]) {
return;
}
if (![self conditionB]) {
return;
}
// some codeA..
// main logic...
}
接口規范
- 保持公有API簡明:對于不想公開的方法和屬性,只在.m文件中聲明實現,.h文件中僅聲明必須公開的方法/屬性。
- 委托模式中聲明的@protocol名稱,需要以委托類名(比如UITableView)開頭,之后加上“Delegate”或“Protocol”。
- @protocol內聲明的方法,需要以委托類名去除項目前綴后的單詞開頭,并且第一個參數需要為委托對象,否則被委托類代理了多個委托時,無法區分該委托方法是由哪個委托對象發起的。
@class CSShareViewController;
@protocol CSShareDelegate <NSObject> // avoid
- (void)shareFinished:(BOOL)isSuccess; // avoid
@end
@class CSShareViewController;
@protocol CSShareViewControllerDelegate <NSObject> // good
- (void)shareViewController:(CSShareViewController *)shareViewController // good
shareFinished:(BOOL)isSuccess;
@end
- 可能失敗,需要拋出error的方法,應該有BOOL返回值表示方法主功能邏輯成功與否。使用該類接口先檢查方法返回值,再依據error進行相應的處理。蘋果API有在成功情況下依舊往error寫入垃圾數據的情況。
// avoid
- (void)methodWithError:(NSError **)error {
// ...
}
- (void)test1 {
NSError *error = nil;
if ([self methodWithError:&error]) { // avoid
// Main Logic
} else {
// Handle Error
}
}
// good
- (BOOL)methodWithError:(NSError **)error {
// ...
}
- (void)test {
NSError *error = nil;
if ([self methodWithError:&error]) { // good
// Main Logic
} else {
// Handle Error
}
}
參考文章:
*《禪與 Objective-C 編程藝術》
我的博客原址:Objective-C編碼規范精選