1.建議用.符號(hào)代替括號(hào)用于設(shè)置或獲取屬性值
For example:
view.backgroundColor = [UIColororangeColor];[UIApplicationsharedApplication].delegate;
Not:
[viewsetBackgroundColor:[UIColororangeColor]];
UIApplication.sharedApplication.delegate;
2.空格
a.縮進(jìn)必須使用4個(gè)空格。沒有縮進(jìn)和制表符怖现。
b.一定要在Xcode中設(shè)置此首選項(xiàng)基矮。方法括號(hào)和其他括號(hào)(如果/其他/開關(guān)/等等)盟萨。必須打開在同一行語(yǔ)句。括號(hào)必須關(guān)閉在一個(gè)新行徙垫。
For example:
if(user.isHappy)?{
//?Do?something
}
else{
//?Do?something?else
}
3.條件語(yǔ)句:必須有括號(hào)
For example:
if(!error) {returnsuccess;}
Not:
if(!error)returnsuccess;
or
if(!error)returnsuccess;
4.三元運(yùn)算符:三元操作符的意圖,?,是增加清晰或代碼整潔腾它。三元應(yīng)該只評(píng)估每一個(gè)條件表達(dá)式乒裆。評(píng)估多個(gè)條件通常是更容易理解作為一個(gè)if語(yǔ)句或重構(gòu)命名變量璃俗。
For example:
result = a > b ? x : y;
Not:
result?=?a?>?b???x?=?c?>?d???c?:?d?:?y;
5.錯(cuò)誤處理:當(dāng)方法返回一個(gè)錯(cuò)誤參數(shù)通過(guò)引用,代碼必須打開返回值,不得打開錯(cuò)誤變量奴璃。
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.分類
類別建議簡(jiǎn)明地細(xì)分功能,用來(lái)描述該功能
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方法應(yīng)放置在頂部的實(shí)現(xiàn),直接放在@ synthesize和@dynamic語(yǔ)句之后。init方法應(yīng)該直接放置在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.在處理位掩碼時(shí),必須使用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.圖片名稱
圖片應(yīng)該命名為一個(gè)駝峰式大小寫字符串的描述他們的目的,其次是無(wú)前綴的名稱他們定制的類或?qū)傩?如果有的話),其次是進(jìn)一步描述顏色和/或位置,最后他們的狀態(tài)。
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.協(xié)議
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;