##背景 這裏有些關於編碼風格Apple官方文檔,若是有些東西沒有說起,能夠在如下文檔來查找更多細節:html
The Objective-C Programming Language : developer.apple.com/library/mac…ios
Cocoa Fundamentals Guide : developer.apple.com/legacy/libr…git
Coding Guidelines for Cocoa : developer.apple.com/library/mac…github
iOS App Programming Guide: developer.apple.com/library/ios…objective-c
##語言 應該使用US英語。 應該: UIColor *myColor = [UIColor whiteColor];
安全
不該該: UIColor *myColour = [UIColor whiteColor];
bash
在函數分組和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 {}
複製代碼
應該:app
if (user.isHappy){
//Do something
} else {
//Do something else
}
複製代碼
不該該:iphone
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
}];
複製代碼
當須要註釋時,註釋應該用來解釋這段特殊代碼爲何要這樣作。任何被使用的註釋都必須保持最新或被刪除。 通常都避免使用塊註釋,由於代碼儘量作到自解釋,只有當斷斷續續或幾行代碼時才須要註釋。例外:這不該用在生成文檔的註釋 Apple命名規則儘量堅持,特別是與這些相關的memory management rules。 長的,描述性的方法和變量命名是好的。
應該: UIButton *settingsButton;
不該該: UIButton *setBut;
三個字符前綴應該常常用在類和常量命名,但在Core Data的實體名中應被忽略。對於官方的raywenderlich.com書、初學者工具包或教程,前綴’RWT’應該被使用。
常量應該使用駝峯式命名規則,全部的單詞首字母大寫和加上與類名有關的前綴。 應該: static NSTimeInterval const RWTTutorialViewControllerNavigationFadeAnimationDuration = 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。 應該:
@interface RWTTutorial : NSObject
@property (strong, nonatomic) NSString *tutorialName;
@end
複製代碼
不該該:
@interface RWTTutorial : 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方法,屬性仍然被訪問或修改。想了解更多,閱讀: developer.apple.com/library/ios… 。 點語法應該老是被用來訪問和修改屬性,由於它使代碼更加簡潔。[]符號更偏向於用在其餘例子。 應該:
objc 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 RWTAboutViewControllerCompanyName = @"RayWenderlich.com";
static CGFloat const RWTImageThumbnailHeight = 50.0;
複製代碼
不該該:
#define CompanyName @"RayWenderlich.com" #define thumbnailHeight 2
複製代碼
當使用enum時,推薦使用新的固定基本類型規格,由於它有更強的類型檢查和代碼補全。如今SDK有一個宏NS_ENUM()來幫助和鼓勵你使用固定的基本類型。 例如:
typedef NS_ENUM(NSInteger, RWTLeftMenuTopItemType) {
RWTLeftMenuTopItemMain,
RWTLeftMenuTopItemShows,
RWTLeftMenuTopItemSchedule
};
複製代碼
你也能夠顯式地賦值(展現舊的k-style常量定義):
typedef NS_ENUM(NSInteger, RWTGlobalConstants) {
RWTPinSizeMin = 1,
RWTPinSizeMax = 5,
RWTPinCountMin = 100,
RWTPinCountMax = 500,
};
複製代碼
舊的k-style常量定義應該避免除非編寫Core Foundation C的代碼。 不該該:
enum GlobalConstants {
kMaxPinSize = 5,
kMaxPinCount = 500,
};
複製代碼
大括號在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’是不須要的。例如:
RWTLeftMenuTopItemType menuType = RWTLeftMenuTopItemMain;
switch (menuType) {
case RWTLeftMenuTopItemMain:
// ...
break;
case RWTLeftMenuTopItemShows:
// ...
break;
case RWTLeftMenuTopItemSchedule:
// ...
break;
}
複製代碼
私有屬性應該在類的實現文件中的類擴展(匿名分類)中聲明,命名分類(好比RWTPrivate或private)應該從不使用除非是擴展其餘類。匿名分類應該經過使用+Private.h文件的命名規則暴露給測試。
例如:
@interface RWTDetailViewController ()
@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方法應該遵循Apple生成代碼模板的命名規則,返回類型應該使用instancetype而不是id。
- (instancetype)init {
self = [super init];
if (self) { // ... }
return self;
}
複製代碼
當類構造方法被使用時,它應該返回類型是instancetype而不是id。這樣確保編譯器正確地推斷結果類型。
@interface Airplane
+ (instancetype)airplaneWithType:(RWTAirplaneType)type;
@end
複製代碼
關於更多instancetype信息,請查看NSHipster.com。
當訪問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分組的建立應該在文件系統的文件體現。代碼不只是根據類型來分組,並且還能夠根據功能來分組,這樣代碼更加清晰。 儘量在target的Build Settings打開」Treat Warnings as Errors,和啓用如下additional warnings。若是你須要忽略特殊的警告,使用Clang’s pragma feature。
【注】本文翻譯自github的objective-c-style-guide,隱去了部分介紹內容,着重點在OC編碼規範知識點。