前段時間接手了一個開發三年之久的老項目,三年期間經歷了5-6個程序員的開發,整個項目架構比較混亂,代碼風格差距很大,也有許多不規范代碼,難以Code Review。對于承擔這個項目的維護、部分代碼重構以及后續產品開發的責任,我擬定了這個遲到了三年之久的項目代碼規范,要求所有的iOS同事在之后的開發以及代碼的重構過程中以此作為編碼規范。此代碼規范一直是我自身的代碼規范,來源于幾年前借鑒 raywenderlich的Objective-C style ,感興趣的朋友可以去GitHub上自行搜索。
命名###
- 變量的命名使用US英語,不可使用拼音代替;
- 盡可能堅持Apple的命名規則,長的,描述性的方法和變量命名是最好的
應該:
UIButton *nextButton;
UIlabel *nameLabel;
或者可以使用簡介的命名方式:
UIButton *btn_next;
UILabel *lb_name;
切不可隨意命名控件:
UIButton *next;
UILabel *name; - 變量的命名采用駝峰命名法則,并且單詞的首字母需要小寫
- 星號表示變量是指針。例如,
NSString *text
既不是NSString* text
也不是NSString * text
,除了一些特殊情況下常量。
下劃線###
- 當使用屬性時,實例變量應該使用self.來訪問和改變。這就意味著所有屬性將會視覺效果不同,因為它們前面都有self.當然,重寫屬性的set,get方法中等必須使用下劃線的情況下使用下劃線.
代碼組織###
-
使用#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 {}
注釋: .h文件中必須要有注釋,標明屬性方法等的含義,.m文件中選擇性適當注釋業務邏輯。當需要注釋時,注釋應該用來解釋這段特殊代碼為什么要這樣做。任何被使用的注釋都必須保持最新或被刪除。
方法之間的間隔
在方法簽名中,應該在方法類型(-/+ 符號)之后有一個空格。在方法各個段之間應該也有一個空格(符合Apple的風格)。在參數之前應該包含一個具有描述性的關鍵字來描述參數。
應該:
- (void)setExampleText:(NSString *)text image:(UIImage *)image;
- (void)sendAction:(SEL)aSelector to:(id)anObject forAllCells:(BOOL)flag;
- (id)viewWithTag:(NSInteger)tag;
- (instancetype)initWithWidth:(CGFloat)width height:(CGFloat)height;
不應該:
-(void)setT:(NSString *)text i:(UIImage *)image;
- (void)sendAction:(SEL)aSelector :(id)anObject :(BOOL)flag;
- (id)taggedView:(NSInteger)tag;
- (instancetype)initWithWidth:(CGFloat)width andHeight:(CGFloat)height;
- (instancetype)initWith:(int)width and:(int)height; // Never do this.在方法之間應該有且只有一行,這樣有利于在視覺上更清晰和更易于組織。在方法內的空白應該分離功能,但通常都抽離出來成為一個新方法。
縮進使用4個空格,確保在Xcode偏好設置來設置,確保代碼對齊。
方法大括號和其他大括號(if/else/switch/while 等.)總是在同一行語句打開但在新行中關閉
應該:
if (user.isHappy) {
//Do something
} else {
//Do something else
}
不應該:
if (user.isHappy)
{
//Do something
}
else {
//Do something else
}應該避免以冒號對齊的方式來調用方法。因為有時方法簽名可能有3個以上的冒號和冒號對齊會使代碼更加易讀。請不要這樣做,盡管冒號對齊的方法包含代碼塊,因為Xcode的對齊方式令它難以辨認。
應該:
// blocks are easily readable
[UIView animateWithDuration:1.0 animations:^{
// something
} completion:^(BOOL finished) {
// something
}];
不應該:
// colon-aligning makes the block indentation hard to read
[UIView animateWithDuration:1.0
animations:^{
// something
}
completion:^(BOOL finished) {
// something
}];
變量###
- 私有變量應該盡可能代替實例變量的使用。盡管使用實例變量是一種有效的方式,但更偏向于使用屬性來保持代碼一致性。
應該:
@interface RWTTutorial : NSObject
@property (strong, nonatomic) NSString *tutorialName;
@end
不應該:
@interface RWTTutorial : NSObject {
NSString *tutorialName;
}
字面值###
- NSString, NSDictionary, NSArray, 和 NSNumber的字面值應該在創建這些類的不可變實例時被使用。請特別注意nil值不能傳入NSArray和NSDictionary字面值,因為這樣會導致crash。
應該:
NSArray *names = @[@"Brian", @"Matt", @"Chris", @"Alex", @"Steve", @"Paul"];
NSDictionary *productManagers = @{@"iPhone": @"Kate", @"iPad": @"Kamal", @"Mobile Web": @"Bill"};
NSNumber *shouldUseLiterals = @YES;
NSNumber *buildingStreetNumber = @10018;
不應該:
NSArray *names = [NSArray arrayWithObjects:@"Brian", @"Matt", @"Chris", @"Alex", @"Steve", @"Paul", nil];
NSDictionary *productManagers = [NSDictionary dictionaryWithObjectsAndKeys: @"Kate", @"iPhone", @"Kamal", @"iPad", @"Bill", @"Mobile Web", nil];
NSNumber *shouldUseLiterals = [NSNumber numberWithBool:YES];
NSNumber *buildingStreetNumber = [NSNumber numberWithInteger:10018];
枚舉類型###
- 當使用enum時,推薦使用新的固定基本類型規格,因為它有更強的類型檢查和代碼補全。現在SDK有一個宏NS_ENUM()來幫助和鼓勵你使用固定的基本類型。
例如:
typedef NS_ENUM(NSInteger, RWTLeftMenuTopItemType) {
RWTLeftMenuTopItemMain,
RWTLeftMenuTopItemShows,
RWTLeftMenuTopItemSchedule
};
或者顯式地賦值:
typedef NS_ENUM(NSInteger, RWTGlobalConstants) {
RWTPinSizeMin = 1,
RWTPinSizeMax = 5,
RWTPinCountMin = 100,
RWTPinCountMax = 500,
};
不應該:
enum GlobalConstants {
kMaxPinSize = 5,
kMaxPinCount = 500,
};
條件語句###
- 只用一行代碼,也應該使用大括號包圍。一方面,可能發生在if語句里面一行代碼被注釋了,然后下一行代碼不知不覺地成為if語句的一部分。另一方面,這種風格與其他條件語句的風格保持一致,所以更加容易閱讀。
應該:
if (!error) {
return success;
}
不應該:
if (!error)
return success;
也不應該:
if (!error) return success;
黃金路徑###
- 當使用條件語句編碼時,不要嵌套if語句,多個返回語句也是OK。
應該:
- (void)someMethod {
if (![someOther boolValue]) {
return;
}
//Do something important
}
不應該:
- (void)someMethod {
if ([someOther boolValue]) {
//Do something important
}
}
Xcode工程###
- 物理文件應該與Xcode工程文件保持同步來避免文件擴張。任何Xcode分組的創建應該在文件系統的文件體現。代碼不僅是根據類型來分組,而且還可以根據功能來分組,這樣代碼更加清晰。