如果你是一位開發人員在開發過程中會發現有些代碼無論是在同一個工程中還是在不同工程中使用率會很高,有經驗的人會直接封裝在一個類裏,或者寫成一個宏定義或者把這些代碼收集起來,下次直接使用,或者放到xcode的代碼片庫裏,直接使用, 從而提高開發效率;
1. 將常用代碼片段封裝成一個類裏
當一個代碼片在一個或多個工程之中經常出現時,把他封裝在一個類裏面,在使用時候直接傳參即可實現對於功能,或者直接把這類放到另一個工程中同樣使用;
使用UIAlertView舉例
創建一個XF_UIKit類,對於聲明文件和實現文件爲
// // XF_UIKit.h // Demo // // Created by DolBy on 13-6-17. // Copyright (c) 2013年 新風作浪. All rights reserved. // #import <Foundation/Foundation.h> @interface XF_UIKit : NSObject +(void)showAlert:(NSString *)title withMessage:(NSString *)message witchCancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSString *)otherButtonTitles, ... NS_REQUIRES_NIL_TERMINATION; @end
// // XF_UIKit.m // Demo // // Created by DolBy on 13-6-17. // Copyright (c) 2013年 新風作浪. All rights reserved. // #import "XF_UIKit.h" @implementation XF_UIKit +(void)showAlert:(NSString *)title withMessage:(NSString *)message witchCancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSString *)otherButtonTitles, ... NS_REQUIRES_NIL_TERMINATION { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:message delegate:self cancelButtonTitle:cancelButtonTitle otherButtonTitles:otherButtonTitles, nil]; [alert show]; [alert release]; } @end
使用的時候引入頭文件直接調用類方法
- (void)viewDidLoad { [super viewDidLoad]; [XF_UIKit showAlert:@"警告" withMessage:@"新風作浪的測試 " witchCancelButtonTitle:@"OK" otherButtonTitles: nil]; // Do any additional setup after loading the view, typically from a nib. }
2.使用宏
在 iOS開發中那些高效常用的宏一文例舉了宏的使用,此處不再贅述;
3.使用Xcode自帶代碼片段庫
在屬性面板下面有一欄庫面板選擇條,有一項Code Snippet Library有iOS下OS X 和 User(用戶自定義的)代碼片段存儲
(1)在這些庫裏有系統自帶的代碼片段,使用的時候直接拖到工程裏,填上參數即可使用。
(2)用戶自定義代碼塊,這也是本文講解的重點。例如:
做過開發的都知道使用表示圖單元格比較頻繁,經常頻繁寫他們的delegate方法,如果把它們收集起來
#pragma mark - #pragma mark UITableViewDataSource and UITableViewDelegate Methods -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ return 10; } -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; } return cell; }
這是繪製一個基本表示圖單元必須實現的協議方法,全選這些代碼拖到Code Snippet Library裏面,如下圖
然後會彈出一個編輯框,然後進行一個簡單編輯,title表示你這個代碼塊標題,Summary 對這段代碼片的簡單介紹,Completion Shortcut表示一個快捷鍵,在我們工程中只要輸入快捷鍵就可以顯示整段代碼片;
相應設置
把參數放在兩個#號之間,比如 #參數#
編輯完畢選擇Done,在User下即可看到TbaleView代碼塊
在使用的時候兩種方式
①直接把這個代碼塊拖到工程中;
②在工程裏面輸入自己設置的快件建代碼,比如剛剛設置的XFTableView,真個代碼塊全部出現;
在資源庫(Libary)/Developer/Xcode/UserData/CodeSnippets下存放的就是你自定義的代碼片段,如果重裝Xcode記得備份哦!