1.建議用.符號代替括號用于設置或獲取屬性值
For example:
view.backgroundColor = [UIColororangeColor];[UIApplicationsharedApplication].delegate;
Not:
[viewsetBackgroundColor:[UIColororangeColor]];
UIApplication.sharedApplication.delegate;
2.空格
a.縮進必須使用4個空格。沒有縮進和制表符。
b.一定要在Xcode中設置此首選項。方法括號和其他括號(如果/其他/開關/等等)。必須打開在同一行語句。括號必須關閉在一個新行。
For example:
if(user.isHappy)?{
//?Do?something
}
else{
//?Do?something?else
}
3.條件語句:必須有括號
For example:
if(!error) {returnsuccess;}
Not:
if(!error)returnsuccess;
or
if(!error)returnsuccess;
4.三元運算符:三元操作符的意圖,?,是增加清晰或代碼整潔。三元應該只評估每一個條件表達式。評估多個條件通常是更容易理解作為一個if語句或重構命名變量。
For example:
result = a > b ? x : y;
Not:
result?=?a?>?b???x?=?c?>?d???c?:?d?:?y;
5.錯誤處理:當方法返回一個錯誤參數通過引用,代碼必須打開返回值,不得打開錯誤變量。
For example:
NSError*error;if(![selftrySomethingWithError:&error]) {// Handle Error}
Not:
NSError*error;[selftrySomethingWithError:&error];if(error) {// Handle Error}
6.方法
For example:
-?(void)setExampleText:(NSString*)text?image:(UIImage?*)image;
7.變量:見名知意
For example:
NSString *title: It is reasonable to assume a “title” is a string.
NSString *titleHTML: This indicates a title that may contain HTML which needs parsing for display.“HTML” is needed for a programmer to use this variable effectively.
NSAttributedString *titleAttributedString: A title, already formatted for display.AttributedStringhints that this value is not just a vanilla title, and adding it could be a reasonable choice depending on context.
NSDate *now:No further clarification is needed.
NSDate *lastModifiedDate: SimplylastModifiedcan be ambiguous; depending on context, one could reasonably assume it is one of a few different types.
NSURL *URLvs.NSString *URLString: In situations when a value can reasonably be represented by different classes, it is often useful to disambiguate in the variable’s name.
NSString *releaseDateString: Another example where a value could be represented by another class, and the name can help disambiguate.
Single letter variable names are NOT RECOMMENDED, except as simple counter variables in loops.
Asterisks indicating a type is a pointer MUST be “attached to” the variable name.For example,NSString *textnotNSString* textorNSString * text, except in the case of constants (NSString * const NYTConstantString).
For example:
interfaceNYTSection:NSObject@property(nonatomic)NSString*headline;@end
Not:
@interfaceNYTSection:NSObject{NSString*headline;}
8.變量限定符:
For example:
NSString * __weak text.
9.命名:描述性的方法和變量名越清楚越好
For example:
UIButton *settingsButton;
Not
UIButton *setBut;
For example:
staticconstNSTimeIntervalNYTArticleViewControllerNavigationFadeAnimationDuration =0.3;
Not:
staticconstNSTimeIntervalfadetime =1.7;
For example:
@synthesize descriptiveVariableName = _descriptiveVariableName;
Not:
idvarnm;
10.分類
類別建議簡明地細分功能,用來描述該功能
For example:
@interfaceUIViewController(NYTMediaPlaying)@interfaceNSString(NSStringEncodingDetection)
Not:
@interfaceNYTAdvertisement(private)
@interfaceNSString(NYTAdditions)
For example:
@interfaceNSArray(NYTAccessors)- (id)nyt_objectOrNilAtIndex:(NSUInteger)index;@end
Not:
@interfaceNSArray(NYTAccessors)
-?(id)objectOrNilAtIndex:(NSUInteger)index;
@end
11.注釋
When they are needed, comments SHOULD be used to explainwhya particular piece of code does something. Any comments that are used MUST be kept up-to-date or deleted.
Block comments are NOT RECOMMENDED, as code should be as self-documenting as possible, with only the need for intermittent, few-line explanations. This does not apply to those comments used to generate documentation.
12.init and dealloc
dealloc方法應放置在頂部的實現,直接放在@ synthesize和@dynamic語句之后。init方法應該直接放置在dealloc任何類的方法。
-?(instancetype)init?{
self?=?[superinit];//?or?call?the?designated?initializer
if(self)?{
//?Custom?initialization
}
returnself;
}
12.文字
For example:
NSArray*names = @[@"Brian",@"Matt",@"Chris",@"Alex",@"Steve",@"Paul"];NSDictionary*productManagers = @{@"iPhone":@"Kate",@"iPad":@"Kamal",@"Mobile Web":@"Bill"};NSNumber*shouldUseLiterals = @YES;NSNumber*buildingZIPCode = @10018;
Not:
NSArray*names?=?[NSArrayarrayWithObjects:@"Brian",@"Matt",@"Chris",@"Alex",@"Steve",@"Paul",nil];
NSDictionary*productManagers?=?[NSDictionarydictionaryWithObjectsAndKeys:@"Kate",@"iPhone",@"Kamal",@"iPad",@"Bill",@"Mobile?Web",nil];
NSNumber*shouldUseLiterals?=?[NSNumbernumberWithBool:YES];
NSNumber*buildingZIPCode?=?[NSNumbernumberWithInteger:10018];
13.CGRECT
For example:
CGRectframe = self.view.frame;CGFloatx = CGRectGetMinX(frame);CGFloaty = CGRectGetMinY(frame);CGFloatwidth = CGRectGetWidth(frame);CGFloatheight = CGRectGetHeight(frame);
Not:
CGRectframe?=?self.view.frame;
CGFloatx?=?frame.origin.x;
CGFloaty?=?frame.origin.y;
CGFloatwidth?=?frame.size.width;
CGFloatheight?=?frame.size.height;
14.常量
For example:
staticNSString*constNYTAboutViewControllerCompanyName =@"The New York Times Company";staticconstCGFloatNYTImageThumbnailHeight =50.0;
Not:
#defineCompanyName@"The?New?York?Times?Company"
#definethumbnailHeight2
15.枚舉
Example:
typedefNS_ENUM(NSInteger,?NYTAdRequestState)?{
NYTAdRequestStateInactive,
NYTAdRequestStateLoading
};
16.在處理位掩碼時,必須使用NS_OPTIONS宏。
Example:
typedefNS_OPTIONS(NSUInteger,?NYTAdCategory)?{
NYTAdCategoryAutos? ? ? =1<<0,
NYTAdCategoryJobs? ? ? ?=1<<1,
NYTAdCategoryRealState? =1<<2,
NYTAdCategoryTechnology?=1<<3
};
17.私有方法:
Private properties SHALL be declared in class extensions (anonymous categories) in the implementation file of a class.
For example:
@interfaceNYTAdvertisement()
@property(nonatomic,strong)?GADBannerView?*googleAdView;
@property(nonatomic,strong)?ADBannerView?*iAdView;
@property(nonatomic,strong)?UIWebView?*adXWebView;
@end
18.圖片名稱
圖片應該命名為一個駝峰式大小寫字符串的描述他們的目的,其次是無前綴的名稱他們定制的類或屬性(如果有的話),其次是進一步描述顏色和/或位置,最后他們的狀態。
For example:
RefreshBarButtonItem/RefreshBarButtonItem@2xandRefreshBarButtonItemSelected/RefreshBarButtonItemSelected@2x
ArticleNavigationBarWhite/ArticleNavigationBarWhite@2xandArticleNavigationBarBlackSelected/ArticleNavigationBarBlackSelected@2x.
18.boolen
Values MUST NOT be compared directly toYES, becauseYESis defined as1, and aBOOLin Objective-C is aCHARtype that is 8 bits long (so a value of11111110will returnNOif compared toYES).
For an object pointer:
if(!someObject) {}if(someObject ==nil) {}
For aBOOLvalue:
if(isAwesome)if(!someNumber.boolValue)if(someNumber.boolValue ==NO)
Not:
if(isAwesome ==YES)// Never do this.
@property?(assign,?getter=isEditable)BOOLeditable;
20.單例
Singleton objects SHOULD use a thread-safe pattern for creating their shared instance.
+?(instancetype)sharedInstance?{
staticidsharedInstance?=nil;
staticdispatch_once_tonceToken;
dispatch_once(&onceToken,?^{
sharedInstance?=?[[[selfclass]alloc]init];
});
returnsharedInstance;
}
21.imports
If there is more than one import statement, statements MUST be groupedtogether. Groups MAY be commented.
Note: For modules use the@importsyntax.
//?Frameworks
@import?QuartzCore;
//?Models
#import"NYTUser.h"
//?Views
#import"NYTButton.h"
#import"NYTUserView.h"
22.協議
In adelegate or data source protocol, the first parameter to each method SHOULD be the object sending the message.
This helps disambiguate in cases when an object is the delegate for multiple similarly-typed objects, and it helps clarify intent to readers of a class implementing these delegate methods.
For example:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath;
Not:
-?(void)didSelectTableRowAtIndexPath:(NSIndexPath*)indexPath;