Xcode的Refactor使用

最近在看《重構》的書,想到Xcode有一個Refactor的功能,不知道您用的多不多,用這個功能在我們開發過程中,可以提高開發效率。

右鍵顯示

一、Rename
重新命名符號,修改屬性或方法的名字。 當然有可能您用的是全域性Replace這個方法,但是這個無法替換Class的檔名 。 演示下將TestViewController的.h .m .xib及用到的地方修改為有意義的命HomeViewController。
1.在TestViewController上右鍵點選,選擇Refactor->Rename

2.將TestViewController修改為HomeViewController,點選Preview。

3.點選檢視並確認,是否是重新命名正確。點選Save,再點選Continue。Rename完成。
4.再去全域性搜尋TestViewController

還有註釋中的未被修改,選擇Replace替換為HomeViewController。
重新命名Property操作也同上。所以看到不符合規範的變數名和方法名及類名,快速的修改吧,提高程式碼的可讀性。
二、 Extract
封裝程式碼。 有時候在鍵盤上健步如飛的敲寫程式碼,發現一個方法中超過了200行的程式碼,要進行方法的分割。如提取通用的程式碼,方法其他方法呼叫。用Extract很簡單。 操作如下:
1.選中需要提取的程式碼,右鍵點選,選中Extract

- (void)extracted_method
New function是新函式,C語言的函式。eg.
void extracted_function()
2.修改方法,點選Preview

點選Save,再選擇Continue。
3.封裝完成
由原來的
- (void)layoutSubviews { [super layoutSubviews]; NSInteger count = [self.subviews count]; for (int i = 0; i < count; i++) { UIButton *btn = self.subviews[i]; btn.tag = i; CGFloat x = i * self.bounds.size.width / count; CGFloat y = 0; CGFloat width = self.bounds.size.width / count; CGFloat height = self.bounds.size.height; btn.frame = CGRectMake(x, y, width, height); } } 複製程式碼
修改為
- (void)updateButtonFrame { NSInteger count = [self.subviews count]; for (int i = 0; i < count; i++) { UIButton *btn = self.subviews[i]; btn.tag = i; CGFloat x = i * self.bounds.size.width / count; CGFloat y = 0; CGFloat width = self.bounds.size.width / count; CGFloat height = self.bounds.size.height; btn.frame = CGRectMake(x, y, width, height); } } - (void)layoutSubviews { [super layoutSubviews]; [self updateButtonFrame]; } 複製程式碼
減少很多複製黏貼。
三、 Create Superclass
建立超類。
. 選中類名,點選右鍵Refactor->Create Superclass

Create files for new superclass: 建立新檔案來建立新類 Add superclass to HomeViewController's files: 在HomeViewController中新增新類。
2. 輸入超類名稱,點選Preview

點選Save,再點選Continue。
3. 修改Superclass的繼承類名
完成
四、 Move Up
將例項變數,property變數或方法移動到超類。 移動方法舉例 方法申明
- (void)updateUserInfo; 複製程式碼
方法實現
- (void)updateUserInfo { NSLog(@"Hello World!"); } 複製程式碼
1. 選中類名, 右鍵點選Refactor->Move Up

2. 點選Preview
啥都沒有顯示,點選Save
3. 方法已經到超類BaseViewController
#import <UIKit/UIKit.h> @interface BaseViewController : UIViewController - (void)updateUserInfo; @end 複製程式碼
五、 Move Down
將例項變數移動到子類。
@interface BaseViewController (){ NSString *schoolNameStr; } 複製程式碼
1. 選中schoolNameStr,右鍵Refactor->Move Down

2. 點選Preview, 再點選Save。
在子類HomeViewController中,可以看到schoolNameStr變數。
@interface HomeViewController : BaseViewController { NSString *schoolNameStr; } 複製程式碼
六、 Encapsulate
建立Setter和Getter方法。 只能對例項變數進行操作,對property無效。
@interface HomeViewController () { NSString *nameStr; } 複製程式碼