語言
使用US英語
代碼組織
在函數分組和protocol/delegate
實現中使用#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 {...}
空格
- 縮進使用4個空格,確保在Xcode偏好設置來設置
- 方法大括號和其他大括號(
if
/else
/switch
/while
等)總是在同一行語句打開但在新行中關閉。 - 注釋
//
后要有空格
應該:
if (user.isHappy) {
// Do something
} else {
// Do something else
}
不應該:
if (user.isHappy)
{
//Do something
}
else {
//Do something else
}
- 在方法之間應該有且只有一行,這樣有利于在視覺上更清晰和更易于組織。在方法內的空白應該分離功能,但通常都抽離出來成為一個新方法。
- 優先使用auto-synthesis。但如果有必要,
@synthesize
和@dynamic
應該在實現中每個都聲明新的一行。 - 應該避免以冒號對齊的方式來調用方法。因為有時方法簽名可能有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
}];
注釋
- 當需要注釋時,注釋應該用來解釋這段特殊代碼為什么要這樣做。任何被使用的注釋都必須保持最新或被刪除。
- 一般都避免使用塊注釋,因為代碼盡可能做到自解釋,只有當斷斷續續或幾行代碼時才需要注釋。
- 注釋
//
后要有空格
應該:
// something
不應該:
//something
命名
Apple命名規則盡可能堅持,特別是與這些相關的memory management rules (NARC)。
長的,描述性的方法和變量命名是好的。
應該:
UIButton *settingsButton;
不應該:
UIButton *setBut;
三個字符前綴應該經常用在類和常量命名,但在Core Data的實體名中應被忽略。前綴'AN'應該被使用。
常量應該使用駝峰式命名規則,所有的單詞首字母大寫和加上與類名有關的前綴。
應該:
static NSTimeInterval const ANTutorialViewControllerNavigationFadeAnimationDuration = 0.3;
不應該:
static NSTimeInterval const fadetime = 1.7;
屬性也是使用駝峰式,但首單詞的首字母小寫。對屬性使用auto-synthesis,而不是手動編寫@synthesize
語句,除非你有一個好的理由。
應該:
@property (strong, nonatomic) NSString *descriptiveVariableName;
不應該:
id varnm;
下劃線
- 當使用屬性時,實例變量應該使用
self.
來訪問和改變。這就意味著所有屬性將會視覺效果不同,因為它們前面都有self.
。 - 但有一個特例:在初始化方法里,實例變量(例如,
_variableName
)應該直接被使用來避免getters
/setters
潛在的副作用。 - 局部變量不應該包含下劃線。
方法
- 在方法簽名中,應該在方法類型(
-/+
符號)之后有一個空格。在方法各個段之間應該也有一個空格(符合Apple的風格)。在參數之前應該包含一個具有描述性的關鍵字來描述參數。 -
and
這個詞的用法應該保留。它不應該用于多個參數來說明,就像initWithWidth:height
以下這個例子:
應該:
- (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.
變量
- 變量盡量以描述性的方式來命名。單個字符的變量命名應該盡量避免,除了在
for()
循環。 - 星號表示變量是指針。例如,
NSString *text
既不是NSString* text
也不是NSString * text
,除了一些特殊情況下常量。 - 私有變量應該盡可能代替實例變量的使用。盡管使用實例變量是一種有效的方式,但更偏向于使用屬性來保持代碼一致性。
- 通過使用
back
屬性(_variable
,變量名前面有下劃線)直接訪問實例變量應該盡量避免,除了在初始化方法(init
,initWithCoder:
, 等…),dealloc
方法和自定義的setters
和getters
。想了解關于如何在初始化方法和dealloc
直接使用Accessor方法的更多信息,查看這里。
應該:
@interface ANTutorial : NSObject
@property (strong, nonatomic) NSString *tutorialName;
@end
不應該:
@interface ANTutorial : NSObject {
NSString *tutorialName;
}
屬性特性
- 所有屬性特性應該顯式地列出來,有助于新手閱讀代碼。屬性特性的順序應該是
storage
、atomicity
,與在Interface Builder
連接UI元素時自動生成代碼一致。
應該:
@property (weak, nonatomic) IBOutlet UIView *containerView;
@property (strong, nonatomic) NSString *tutorialName;
不應該:
@property (nonatomic, weak) IBOutlet UIView *containerView;
@property (nonatomic) NSString *tutorialName;
NSString
應該使用copy
而不是strong
的屬性特性。
為什么?即使你聲明一個NSString
的屬性,有人可能傳入一個NSMutableString
的實例,然后在你沒有注意的情況下修改它。
應該:
@property (copy, nonatomic) NSString *tutorialName;
不應該:
@property (strong, nonatomic) NSString *tutorialName;
點符號語法
- 點語法是一種很方便封裝訪問方法調用的方式。當你使用點語法時,通過使用
getter
或setter
方法,屬性仍然被訪問或修改。想了解更多,閱讀這里。 - 點語法應該總是被用來訪問和修改屬性,因為它使代碼更加簡潔。
[]
符號更偏向于用在其他例子。
應該:
NSInteger arrayCount = [self.array count];
view.backgroundColor = [UIColor orangeColor];
[UIApplication sharedApplication].delegate;
不應該:
NSInteger arrayCount = self.array.count;
[view setBackgroundColor:[UIColor orangeColor]];
UIApplication.sharedApplication.delegate;
字面值
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];
常量
常量是容易重復被使用和無需通過查找和代替就能快速修改值。常量應該使用static
來聲明而不是使用#define
,除非顯式地使用宏。
應該:
static NSString * const ANAboutViewControllerCompanyName = @"xinshui.com";
static CGFloat const ANImageThumbnailHeight = 50.0;
不應該:
#define CompanyName @"xinshui.com"
#define thumbnailHeight 2
枚舉類型
當使用enum
時,推薦使用新的固定基本類型規格,因為它有更強的類型檢查和代碼補全。現在SDK有一個宏NS_ENUM()
來幫助和鼓勵你使用固定的基本類型。
例如:
typedef NS_ENUM(NSInteger, ANLeftMenuTopItemType) {
ANLeftMenuTopItemMain,
ANLeftMenuTopItemShows,
ANLeftMenuTopItemSchedule
};
你也可以顯式地賦值(展示舊的k-style
常量定義):
typedef NS_ENUM(NSInteger, ANGlobalConstants) {
ANPinSizeMin = 1,
ANPinSizeMax = 5,
ANPinCountMin = 100,
ANPinCountMax = 500,
};
舊的k-style
常量定義應該避免除非編寫Core Foundation C的代碼。
不應該:
enum GlobalConstants {
kMaxPinSize = 5,
kMaxPinCount = 500,
};
Case語句
大括號在case
語句中并不是必須的,除非編譯器強制要求。當一個case
語句包含多行代碼時,大括號應該加上。
switch (condition) {
case 1:
// ...
break;
case 2: {
// ...
// Multi-line example using braces
break;
}
case 3:
// ...
break;
default:
// ...
break;
}
有很多次,當相同代碼被多個cases
使用時,一個fall-through
應該被使用。一個fall-through
就是在case
最后移除break
語句,這樣就能夠允許執行流程跳轉到下一個case
值。為了代碼更加清晰,一個fall-through
需要注釋一下。
switch (condition) {
case 1:
// fall-through!
case 2:
// code executed for values 1 and 2
break;
default:
// ...
break;
}
當在switch
使用枚舉類型時,default
是不需要的。
例如:
ANLeftMenuTopItemType menuType = ANLeftMenuTopItemMain;
switch (menuType) {
case ANLeftMenuTopItemMain:
// ...
break;
case ANLeftMenuTopItemShows:
// ...
break;
case ANLeftMenuTopItemSchedule:
// ...
break;
}
私有屬性
私有屬性應該在類的實現文件中的類擴展(匿名分類)中聲明,命名分類(比如ANPrivate
或private
)應該從不使用除非是擴展其他類。匿名分類應該通過使用<headerfile>+Private.h
文件的命名規則暴露給測試。
例如:
@interface ANDetailViewController ()
@property (strong, nonatomic) GADBannerView *googleAdView;
@property (strong, nonatomic) ADBannerView *iAdView;
@property (strong, nonatomic) UIWebView *adXWebView;
@end
布爾值
Objective-C使用YES
和NO
。因為true
和false
應該只在CoreFoundation,C或C++代碼使用。既然nil
解析成NO,所以沒有必要在條件語句比較。不要拿某樣東西直接與YES
比較,因為YES
被定義為1
和一個BOOL
能被設置為8位。
- 這是為了在不同文件保持一致性和在視覺上更加簡潔而考慮。
應該:
if (someObject) {}
if (![anotherObject boolValue]) {}
不應該:
if (someObject == nil) {}
if ([anotherObject boolValue] == NO) {}
if (isAwesome == YES) {} // Never do this.
if (isAwesome == true) {} // Never do this.
如果BOOL
屬性的名字是一個形容詞,屬性就能忽略is前綴,但要指定get
訪問器的慣用名稱。
例如:
@property (assign, getter=isEditable) BOOL editable;
文字和例子從這里引用Cocoa Naming Guidelines。
條件語句
條件語句主體為了防止出錯應該使用大括號包圍,即使條件語句主體能夠不用大括號編寫(如,只用一行代碼)。這些錯誤包括添加第二行代碼和期望它成為if
語句;還有,even more dangerous defect可能發生在if
語句里面一行代碼被注釋了,然后下一行代碼不知不覺地成為if
語句的一部分。除此之外,這種風格與其他條件語句的風格保持一致,所以更加容易閱讀。
應該:
if (!error) {
return success;
}
不應該:
if (!error)
return success;
if (!error) return success;
三元操作符
當需要提高代碼的清晰性和簡潔性時,三元操作符?:
才會使用。單個條件求值常常需要它。多個條件求值時,如果使用if語句或重構成實例變量時,代碼會更加易讀。一般來說,最好使用三元操作符是在根據條件來賦值的情況下。
Non-boolean
的變量與某東西比較,加上括號()
會提高可讀性。如果被比較的變量是boolean
類型,那么就不需要括號。
應該:
NSInteger value = 5;
result = (value != 0) ? x : y;
BOOL isHorizontal = YES;
result = isHorizontal ? x : y;
不應該:
result = a > b ? x = c > d ? c : d : y;
Init方法
Init
方法應該遵循Apple生成代碼模板的命名規則,返回類型應該使用instancetype
而不是id
。
- (instancetype)init {
self = [super init];
if (self) {
// ...
}
return self;
}
類構造方法
當類構造方法被使用時,它應該返回類型是instancetype
而不是id
。這樣確保編譯器正確地推斷結果類型。
@interface Airplane
+ (instancetype)airplaneWithType:(ANAirplaneType)type;
@end
關于更多instancetype
信息,請查看NSHipster.com。
CGRect函數
當訪問CGRect
里的x
,y
,width
,或height
時,應該使用CGGeometry
函數而不是直接通過結構體來訪問。引用Apple的CGGeometry:
在這個參考文檔中所有的函數,接受CGRect
結構體作為輸入,在計算它們結果時隱式地標準化這些rectangles。因此,你的應用程序應該避免直接訪問和修改保存在CGRect
數據結構中的數據。相反,使用這些函數來操縱rectangles和獲取它們的特性。
應該:
CGRect frame = self.view.frame;
CGFloat x = CGRectGetMinX(frame);
CGFloat y = CGRectGetMinY(frame);
CGFloat width = CGRectGetWidth(frame);
CGFloat height = CGRectGetHeight(frame);
CGRect frame = CGRectMake(0.0, 0.0, width, height);
不應該:
CGRect frame = self.view.frame;
CGFloat x = frame.origin.x;
CGFloat y = frame.origin.y;
CGFloat width = frame.size.width;
CGFloat height = frame.size.height;
CGRect frame = (CGRect){ .origin = CGPointZero, .size = frame.size };
黃金路徑
當使用條件語句編碼時,左手邊的代碼應該是"golden" 或 "happy"路徑。也就是不要嵌套if語句,多個返回語句也是OK。
應該:
- (void)someMethod {
if (![someOther boolValue]) {
return;
}
// Do something important
}
不應該:
- (void)someMethod {
if ([someOther boolValue]) {
// Do something important
}
}
錯誤處理
當方法通過引用來返回一個錯誤參數,判斷返回值而不是錯誤變量。
應該:
NSError *error;
if (![self trySomethingWithError:&error]) {
// Handle Error
}
不應該:
NSError *error;
[self trySomethingWithError:&error];
if (error) {
// Handle Error
}
在成功的情況下,有些Apple的APIs記錄垃圾值(garbage values)
到錯誤參數(如果non-NULL
),那么判斷錯誤值會導致false``負值
和crash。
單例模式
單例對象應該使用線程安全模式來創建共享實例。
+ (instancetype)sharedInstance {
static id sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}
這會防止possible and sometimes prolific crashes。
換行符
換行符是一個很重要的主題,因為它的風格指南主要為了打印和網上的可讀性。
例如:
self.productsRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:productIdentifiers];
一行很長的代碼應該分成兩行代碼,下一行用兩個空格隔開。
self.productsRequest = [[SKProductsRequest alloc]
initWithProductIdentifiers:productIdentifiers];
Xcode工程
物理文件應該與Xcode工程文件保持同步來避免文件擴張。任何Xcode分組的創建應該在文件系統的文件體現。代碼不僅是根據類型來分組,而且還可以根據功能來分組,這樣代碼更加清晰。