iOS開發代碼規範

來源:互聯網
上載者:User

標籤:導致   xcode   事件   nsstring   函數返回   float   ges   geo   mutable   

  作為一名合格的編碼人員, 特別是打算以後長時間從事IT這一行業的人來說, 應該要明確一點: 我們寫的代碼不只是寫給自己看的, 優雅的編碼風格以及良好的代碼注釋對我們日常的開發是十分有必要的. 當我們在編寫代碼時, 要有一個意識: 此刻有千千萬萬的人正在看著自己寫代碼, 如何讓他們都能快速看懂自己寫的代碼, 這就需要我們在平常開發的時候, 時時刻刻都要進行代碼規範.

 

  • 命名規範
    • 常量
      • 常量應該使用相關的類的名字作為首碼, 並使用駝峰命名法
// 正例:static NSStirng * const HomeViewControllerDidReceiveRefreshNotification = @”HomeViewControllerDidReceiveRefreshNotification”;    // 反例: static NSString * const refresh = @”refresh”;
    • 枚舉
      • 枚舉的命名應準確地描述該枚舉的意義, 並使用駝峰命名法
      • 枚舉中的各個值都應以定義的枚舉類型開頭, 其後跟隨著枚舉值對應的狀態、選項或者類型.
typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) {    AFNetworkReachabilityStatusUnknown = -1,    AFNetworkReachabilityStatusNotReachable = 0,    AFNetworkReachabilityStatusReachableViaWWAN = 1,    AFNetworkReachabilityStatusReachableViaWiFi = 2};
    • 通知
      • 通知常用於模組間傳遞訊息, 所以通知要儘可能地表示出發生的事件
      • [觸發通知的類名] + [Did | Will] + [動作] + Notification
NSApplicationDidBecomeActiveNotificationNSWindowDidMiniaturizeNotificationNSTextViewDidChangeSelectionNotificationNSColorPanelColorDidChangeNotification
    • 代理
      • 類型執行個體必須為回調方法的參數之一
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
      • 回調方法的參數應該只包含類自己的情況, 方法名要符合實際含義
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;
      • 以類的名字開頭(回調方法存在兩個以上參數的情況)以表明此方法是屬於哪個類的
- (NSInteger)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
      • 使用 did 和 will 通知 Delegate 已經發生的變化或將要發生的變化
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath;- (NSIndexPath *)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;
    • 函數
      • 函數名稱一般帶有縮寫首碼, 表示方法所在的架構
      • 函數首碼後的單詞以駝峰標記法顯示, 第一個單字首大寫
      • 函數名的第一個單詞是一個動詞, 表示方法執行的操作
NSHighlightRectNSDeallocateObject
      • 如果函數返回其參數的某個屬性, 省略動詞
unsigned int NSEventMaskFromType(NSEventType type)float NSHeight(NSRect aRect)
      • 如果函數通過指標來傳回值, 需要在函數名中便利 Get
const char *NSGetSizeAndAlignment(const char *typePtr, unsigned int *sizep, unsigned int *alignp)
      • 函數的傳回型別是 BOOL 時的命名
BOOL NSDecimalIsNotANumber(const NSDecimal *decimal)
    • 方法
      • 命名應該儘可能地清晰和簡潔, 特點在 Object-C 中, 清晰比簡潔更重要, 由於 Xcode 強大的自動補全功能, 我們不必擔心名稱過長的問題
//清晰insertObject:atIndex://不清晰,insert的物件類型和at的位置屬性沒有說明insert:at://清晰removeObjectAtIndex://不清晰,remove的物件類型沒有說明,參數的作用沒有說明remove:
      • 不要使用單詞的簡寫, 拼字出完整的單詞
//清晰destinationSelectionsetBackgroundColor: //不清晰,不要使用簡寫destSelsetBkgdColor:
      • 如果方法表示讓對象執行一個動作, 使用動詞打頭來命名, 注意不要使用 do, dose 這種多餘的關鍵字, 動詞本身的暗示就足夠了
//動詞打頭的方法表示讓對象執行一個動作- (void)invokeWithTarget:(id)target;- (void)selectTabViewItem:(NSTabViewItem *)tabViewItem;
      • 如果方法是為了擷取對象的一個屬性值, 直接用屬性名稱來命名這個方法, 注意不要添加 get 或者或者其它動詞首碼
//正確,使用屬性名稱來命名方法- (NSSize)cellSize; //錯誤,添加了多餘的動詞首碼- (NSSize)calcCellSize;- (NSSize)getCellSize;
      • 可以使用 can, should, will, did 等詞來協助表達存取方法的意思, 但不要使用 do, dose
//正確- (void)setCanHide:(BOOL)flag;- (BOOL)canHide;- (void)setShouldCloseDocument:(BOOL)flag;- (BOOL)shouldCloseDocument; //錯誤,不要使用"do"或者"does"- (void)setDoesAcceptGlyphInfo:(BOOL)flag;- (BOOL)doesAcceptGlyphInfo;

 

 

  • 代碼注釋
    • 使用 #pragma mark - 方式對方法進行分組
 #pragma mark - private methods- (void)samplePrivateMethod{...}- (void)sampleForIf{...}
- (void)sampleForWhile{...}   - (void)sampleForSwitch{...}- (void)wrongExamples{...}#pragma mark - public methods- (void)samplePublicMethodWithParam:(NSString*)sampleParam{...}#pragma mark - life cycle methods- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{...}- (void)viewDidLoad{...}
    • 方法聲明注釋
#pragma mark - ?? 註冊介面 ?? ??/** *  註冊介面 * *  @param mobilePhone 註冊手機號號 *  @param areaId      手機地區號ID *  @param code        驗證碼 *  @param pwd         註冊密碼 */- (NSURLSessionDataTask *)registerWithMobilePhone:(NSString *)mobilePhone                                         areaId:(NSString *)areaId                                             code:(NSString *)code                                             pwd:(NSString *)pwd                                           success:(SuccessBlock)success                                           failure:(FailureBlock)failure;

 

 

  • 編碼風格
    • 不要使用 new 方法
      • 儘管很多時候用 new 代替 alloc init 方法, 但是這可能導致高度記憶體時出現不可預料的問題, 並且 Cocoa 的規範就是使用 alloc init 方法, 使用 new 會讓一些讀者困惑  
    • Public API 要盡量簡潔
      • 共有的介面要設計得簡潔, 滿足核心的功能需求就可以了, 不要設計很少會被用到並且參數極其複雜的 API , 如果定義複雜的方法, 使用類別或者拓展
    • 在 init 和 dealloc 方法中盡量不要用存取方法訪問執行個體變數
      • 當 init 和 dealloc 方法被執行時, 類的運行時環境不是正常狀態的, 使用存取方法訪問變數可能會導致不可預料的結果, 因此應當在兩個方法內直接存取執行個體變數
//正確,直接存取執行個體變數- (instancetype)init {  self = [super init];  if (self) {    _bar = [[NSMutableString alloc] init];  }  return self;}- (void)dealloc {  [_bar release];  [super dealloc];} //錯誤,不要通過存取方法訪問- (instancetype)init {  self = [super init];  if (self) {    self.bar = [NSMutableString string];  }  return self;}- (void)dealloc {  self.bar = nil;  [super dealloc];}
    • 保證 NSString 在賦值時被複製
- (void)setFoo:(NSString *)aFoo {  _foo = [aFoo copy];}
    • 當使用一個 CGRect 函數的 x, y, width, height 時, 應該使用 [CGGeometry 函數][CGGeometry-Functions_1]代替直接存取結構體成員
// 正例:CGRect frame = self.view.frame;CGFloat x      = CGRectGetMinX(frame);CGFloat y      = CGRectGetMinY(frame);CGFloat width  = CGRectGetWidth(frame);CGFLoat height = CGRectGetHeight(frame); // 反例: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;      
    • 嵌套判斷
// 正例:if (!user.UserName) return NO;if (!user.Password) return NO;if (!user.Email) return NO;return YES; // 反例: BOOL isValid = NO;if (user.UserName){    if (user.Password)    {        if (user.Email) isValid = YES;    }}return isValid;

 

iOS開發代碼規範

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.