代碼組織
在函數分組和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偏好設置來設置。(raywenderlich.com使用2個空格)
- 方法大括號和其他大括號(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
}];
命名
三個字符前綴應該經常用在類和常量命名,但在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()循環。
屬性特性
所有屬性特性應該顯式地列出來,有助于新手閱讀代碼。屬性特性的順序應該是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;
點符號語法
點語法應該總是被用來訪問和修改屬性,因為它使代碼更加簡潔。[]
符號更偏向于用在其他例子。
應該:
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語句中并不是必須的,除非編譯器強制要求。當一個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。
單例模式
單例對象應該使用線程安全模式來創建共享實例。
+ (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];