1-語言:使用US英語
UIColor *myColor = [UIColor whiteColor];
2-代碼組織
在函數分組和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{}
3-空格
縮進使用4個空格,確保在xcode偏好設置來設置
4-注釋
當需要注釋時,注釋應該用來解釋這段特殊代碼為什么要這樣。任何被使用的注釋都必須保持最新
5-命名
Apple命名規則盡可能堅持,描述性方法和變量命名是好的
UIButton *settingButton;
6-下劃線
當使用屬性時,實例變量應該使用self.來訪問和改變。
特例:在初始化方法里,實例變量(_variableName)應該直接被使用
局部變量不應該包含下劃線
7-方法
+/-方法 之后有一個空格,在參數之前應該包含一個具體描述性的關鍵字來描述參數
(void)sendAction:(SEL)selector to:(id)object forAllCells:(BOOL)flag;
8-變量
變量盡量以描述性的方式來命名。 *表示是指針
私有變量應該盡可能代替實例變量的使用。
@interface Photo:NSObject
@property (strong, nonatomic) NSString *url;
@end
not
@interface Photo:NSObject{
NSString *tutorialName;
}
9-屬性特性
所有屬性特性應該顯示地列出來
點符號語法
點語法是一種很方便封裝訪問方法調用的方式。
10-常量
常量是容易重復被使用和無需通過查找和代替就能快速修改值; 使用static而不是#define
static CGFloat const RWImageHeight = 50.0
not #define RWImageHeight ?50.0
11-枚舉類型
使用enum時, 基本是
typedef NS_ENUM(NSInteger, LeftMenuTopType){
};
12-case語句
當一個case語句包含多行代碼時,大括號加上
13-布爾值
object-c使用YES and NO; true and false 應該只在CoreFoundation c and c++使用
14-條件語句 使用{}
15-三元操作符
16-Init方法
init方法應該遵循Apple生成代碼模板的命名規則,返回類型使用instancetype不是id
17-類構造方法
當類構造方法被使用時,返回類型是instancetype而不是id;
@interface Airplane
+ (instancetype)airplaneWithType:(AirplaneType)type;
@end
18-錯誤處理
當方法通過引用來返回一個錯誤參數,判斷返回值不是錯誤變量
NSError *error;
if(![self trySomethingWithError:&error]){
//handle error
}
19-單例模式
單例對象應該使用線程安全模式創建共享實例
+ (instancetype)sharedInstance {
? ? ? ? ?static id sharedInstance = nil;
? ? ? ? ?static dispatch_once_t onceToken;
? ? ? ? ? dispatch_once(&onceToken, ^{
? ? ? ? ?sharedInstance = [[self alloc] init];
? ? });
? ? ? ?return sharedInstance;
}
20-xcode工程
盡可能在target的Build Settings打開”Treat Warnings as Errors,和啟用以下additional warnings。如果你需要忽略特殊的警告,使用Clang’s pragma feature