目的
統(tǒng)一規(guī)范Xcode編輯環(huán)境下 Object-C 的編程風(fēng)格和標(biāo)準(zhǔn),盡量遵循蘋果公司發(fā)布代碼中的主流代碼風(fēng)格。
Xcode 一般工程目錄結(jié)構(gòu)
-
例:
CarPurifier -README.md -CarPurifier --CarPurifierApi --Resources --Macro --General --Helpers --Models --Sections ---UserInfomationVCtrl . . --Vendors --Utility --Services . . . Pods -Podfile . .
文件及模塊命名及結(jié)構(gòu)管理
文件夾及文件創(chuàng)建 相應(yīng)字母必須大寫. 例: UserInfomationVCtrl。
禁止在項(xiàng)目中的任何地方,包括文件名、目錄名、邏輯目錄名、項(xiàng)目名,使用空格或中文字符。
資源文件plist,image,audio,video,buddle等相關(guān)資源 一律放入Resources文件夾,并建立對(duì)應(yīng)文件夾.如有其他特殊情況,在相關(guān)文件下 做好備注。
第三方的類庫(kù)/SDK,如UMeng、WeiboSDK、WeixinSDK及相關(guān)第三方開源庫(kù) 等專門存放在固定文件夾Vendors中,每個(gè)第三方庫(kù)應(yīng)該有屬于自己的文件夾
自定義公用類 放入 General 文件夾 命名方式 例:ADMainButton,ADWalkthroughTextField,AD代表阿迪的首字母表示 構(gòu)建者
項(xiàng)目APP公用定義 如枚舉、消息通知、宏 放入 Macro文件夾
備注:其他根據(jù)項(xiàng)目需求而定
書寫規(guī)范
Xcode 工程
物理文件應(yīng)該與Xcode工程文件保持同步來避免文件擴(kuò)張。任何Xcode分組的創(chuàng)建應(yīng)該在文件系統(tǒng)的文件體現(xiàn)。代碼不僅是根據(jù)類型來分組,而且還可以根據(jù)功能來分組,這樣代碼更加清晰。
盡可能在target的Build Settings打開”Treat Warnings as Errors,和啟用以下additional warnings。如果你需要忽略特殊的警告,使用Clang’s pragma feature。
代碼組織
在函數(shù)分組和protocol/delegate實(shí)現(xiàn)中使用#pragma mark -來分類方法,要遵循以下一般結(jié)構(gòu):
#pramma 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 {}
Whitespace
對(duì)齊方式 就按 Xcode 默認(rèn)縮進(jìn)方式吧
- 包含 依賴文件的時(shí)候,最好 分清晰
///系統(tǒng)框架
#import <Foundation/Foundation.h>
#import <StoreKit/StoreKit.h>
///pods
#import <AFNetworking/AFNetworking.h>
///
#import "SomeDependency.h"
#import "SomeOtherDependency.h"
@interface UserLoginCtrl ()
括號(hào)
- 方法大括號(hào)和其他大括號(hào)(if/else/switch/while 等.)總是在同一行語(yǔ)句打開但在新行中關(guān)閉
建議寫法
if(condition){
///do something
}
else{
///do something
}
不建議寫法
if(condition)
{
///do something
}
else
{
///do something
}
注釋
建議寫法
/**
@brief 方法或變量名說明
@param 參數(shù)1說明
@param 參數(shù)2說明
…
@return 若方法又返回值則對(duì)返回值作說明
*/
+ (NSString *)uuid:(NSString *)param;
///用戶名
@property (nonatomic, strong) ADWalkthroughTextField *usernameField;
///頭像 圖標(biāo)
@property (nonatomic, strong) UIImageView *headIcon;
或者
/*
* 密碼
*/
@property (nonatomic, strong) UITextField *passwordField;
- 備注: xcode 注釋插件 https://github.com/onevcat/VVDocumenter-Xcode
命名
命名盡量簡(jiǎn)潔,但不能因?yàn)楹?jiǎn)潔而使命名難以理解
建議寫法
UIButton *settingButton;
UILabel *titleLabel;
UITextField *detailTextField;
UITextView *valueTextView;
不建議寫法
UIButton *settingBtn; 或者 UIButton *settingBut;
UILabel *titleLbl; 或者 UIButton *titleLab;
UITextField *detailField;
UITextView *valueTView;
常量命名規(guī)則(駝峰式命名規(guī)則),所有的單詞首字母大寫和加上與類名有關(guān)的前綴:
建議寫法
CGFloat const GeneralWalkthroughStandardOffset = 15.0;
static CGFloat const GeneralWalkthroughSecondaryButtonHeight = 33.0;
NSTimeInterval const GeneralWalkthroughAnimationDuration = 0.3f;
UIEdgeInsets const CreateAccountBackButtonPadding = {1.0, 0.0, 0.0, 0.0};
不建議寫法
CGFloat const tandardOffset = 15.0;
static CGFloat const ButtonHeight = 33.0;
NSTimeInterval const Duration = 0.3f;
屬性也是使用駝峰式,但首單詞的首字母小寫:
@property (strong, nonatomic) NSString *descriptiveVariableName;
或者 @property (copy, nonatomic) NSString *descriptiveVariableName;
注:屬性的聲明和實(shí)現(xiàn),盡量避免書寫@synthesize,如果用到@synthesize,要緊接著@implementation書寫,不要空行
當(dāng)使用屬性時(shí),實(shí)例變量應(yīng)該使用self.來訪問和改變。這就意味著所有屬性將會(huì)視覺效果不同,因?yàn)樗鼈兦懊娑加衧elf.。
但有一個(gè)特例:在初始化方法里,實(shí)例變量(例如,_variableName)應(yīng)該直接被使用來避免getters/setters潛在的副作用。
局部變量不應(yīng)該包含下劃線。成員變量盡量寫在@implementation內(nèi)部,有必要對(duì)外暴露時(shí)(或者 .m 中@interface),才寫在@interface下
對(duì)于聲明 NSString的屬性,還是用 copy 特性,原因度娘 谷歌。
方法
寫方法的風(fēng)格 例如 Apple 的風(fēng)格: - (void)addSubview:(UIView *)view;
建議寫法
- (NSString *)name;
- (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;
不建議寫法
- (NSString *)getName;
- (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.
點(diǎn)語(yǔ)法
修改屬性 : setter 和 getter
Apple文檔:
建議寫法
NSInteger arrayCount = [self.array count];
view.backgroundColor = [UIColor orangeColor];
[UIApplication sharedApplication].delegate;
不建議寫法
NSInteger arrayCount = self.array.count;
[view setBackgroundColor:[UIColor orangeColor]];
UIApplication.sharedApplication.delegate;
簡(jiǎn)寫
NSDictionary、NSArray和NSNumber 的簡(jiǎn)寫
建議寫法
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];
常量定義
建議寫法
局部 定義(當(dāng)前文件)
CGFloat const CreateAccountIOS7StatusBarOffset = 20.0;
NSString *const UMAPP_KEY =@"55d3de82e0f55a54fd004dad";
全局 定義(重復(fù)使用)
static CGFloat const CreateAccountIOS7StatusBarOffset = 20.0;
static NSString *const UMAPP_KEY =@"55d3de82e0f55a54fd004dad";
不建議寫法
#define CreateAccountIOS7StatusBarOffset 20.0;
#define UMAPP_KEY @"55d3de82e0f55a54fd004dad"
枚舉類型 定義
當(dāng)使用enum時(shí),推薦使用新的固定基本類型規(guī)格,因?yàn)樗懈鼜?qiáng)的類型檢查和代碼補(bǔ)全
建議寫法
typedef NS_ENUM(NSInteger, MBProgressHUDAnimation) {
/** Opacity animation */
MBProgressHUDAnimationFade,
/** Opacity + scale animation */
MBProgressHUDAnimationZoom,
MBProgressHUDAnimationZoomOut = MBProgressHUDAnimationZoom,
MBProgressHUDAnimationZoomIn
};
或者
typedef NS_OPTIONS(NSUInteger, UIViewAutoresizing) {
UIViewAutoresizingNone = 0,
UIViewAutoresizingFlexibleLeftMargin = 1 << 0,
UIViewAutoresizingFlexibleWidth = 1 << 1,
UIViewAutoresizingFlexibleRightMargin = 1 << 2,
UIViewAutoresizingFlexibleTopMargin = 1 << 3,
UIViewAutoresizingFlexibleHeight = 1 << 4,
UIViewAutoresizingFlexibleBottomMargin = 1 << 5
};
或者
typedef NS_ENUM(NSInteger, RWTGlobalConstants) {
RWTPinSizeMin = 1,
RWTPinSizeMax = 5,
RWTPinCountMin = 100,
RWTPinCountMax = 500,
};
-
注: 當(dāng)用到 CoreFoundation C code 或者 C++ code 時(shí),可以使用
enum GlobalConstants { kMaxPinSize = 5, kMaxPinCount = 500; };
條件判斷
BOOL類型: Objective-C使用YES和NO。因?yàn)閠rue和false應(yīng)該只在CoreFoundation,C或C++代碼使用。既然nil解析成NO,所以沒有必要在條件語(yǔ)句比較。不要拿某樣?xùn)|西直接與YES比較,因?yàn)閅ES被定義為1和一個(gè)BOOL能被設(shè)置為8位。
建議寫法:
if(isBool){
/// do something
}
if(![String isEqualToString:@"string" ]){
/// do something
}
-
注: 如果BOOL屬性的名字是一個(gè)形容詞,屬性就能忽略”is”前綴,但要指定get訪問器的慣用名稱
@property (assign, getter=isEditable) BOOL editable;
Object 類型: 當(dāng)判斷為nil 時(shí)
建議寫法
if(object == nil){
/// do something
}
不建議寫法
if(object){
/// do something
}
判端 delegate 是否存在時(shí)
建議寫法
if([self.delegate conformsToProtocol:@protocol(RESideMenuDelegate)] &&
[self.delegate respondsToSelector:@selector(sideMenu:willShowMenuViewController:)){
/// do something
}
不建議寫法
if(delegate){
/// do something
}
- 當(dāng)條件只中帶有 return 時(shí)
建議寫法
if (!error) {
return success;
}
不建議寫法
if (!error)
return success;
或者
if (!error) return success;
三元操作符
當(dāng)需要提高代碼的清晰性和簡(jiǎn)潔性時(shí),三元操作符?:才會(huì)使用。單個(gè)條件求值常常需要它。多個(gè)條件求值時(shí),如果使用if語(yǔ)句或重構(gòu)成實(shí)例變量時(shí),代碼會(huì)更加易讀。一般來說,最好使用三元操作符是在根據(jù)條件來賦值的情況下。
Non-boolean的變量與某東西比較,加上括號(hào)()會(huì)提高可讀性。如果被比較的變量是boolean類型,那么就不需要括號(hào)。
建議寫法
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方法應(yīng)該遵循Apple生成代碼模板的命名規(guī)則,返回類型應(yīng)該使用instancetype而不是id。
- (instancetype)init {
self = [super init];
if (self) {
// ...
}
return self;
}
類構(gòu)造方法
同 Init 方法
@interface Airplane
+ (instancetype)initWithType:(ADViewTpye)type
- (instancetype)initWithLeftViewImage:(UIImage *)image;
@end
- 注: 可以看看 http://NSHipster.com
Dealloc Methods
Dealloc 方法在ARC 下 已經(jīng)不再需要,但在某些情況下必須使用以除去observers,KVO等
- (void)dealloc{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
CGRect函數(shù)
當(dāng)訪問CGRect里的x, y, width, 或 height時(shí),應(yīng)該使用CGGeometry函數(shù)而不是直接通過結(jié)構(gòu)體來訪問。引用Apple的CGGeometry:
- 在這個(gè)參考文檔中所有的函數(shù),接受CGRect結(jié)構(gòu)體作為輸入,在計(jì)算它們結(jié)果時(shí)隱式地標(biāo)準(zhǔn)化這些rectangles。因此,你的應(yīng)用程序應(yīng)該避免直接訪問和修改保存在CGRect數(shù)據(jù)結(jié)構(gòu)中的數(shù)據(jù)。相反,使用這些函數(shù)來操縱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 Path
當(dāng)使用條件語(yǔ)句編碼時(shí),左手邊的代碼應(yīng)該是”golden” 或 “happy”路徑。也就是不要嵌套if語(yǔ)句,多個(gè)返回語(yǔ)句也是OK。
建議寫法
- (void)someMethod {
if (![someOther boolValue]) {
return;
}
//Do something important
}
Error handling
Singletons 單例
+ (instancetype)sharedInstance {
static id sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}