描述:
我們有沒有好奇過,我們寫代碼的時(shí)候輸入幾個(gè)字母系統(tǒng)就會(huì)提示一些相應(yīng)的代碼塊。比如- (instancetype)initWithFrame:(CGRect)frame等。但是還有些我們常用的代碼塊系統(tǒng)是沒有的。這個(gè)時(shí)候我們就需要自己自定義一些代碼塊了。
自定義代碼塊的方法:
1.首先在項(xiàng)目中寫入自己想創(chuàng)建成為Code Snippets的代碼塊。如:
@property (nonatomic, assign) <#Type#> <#name#>;
2.選中代碼塊點(diǎn)擊鼠標(biāo)右鍵選中create Code snippet 選項(xiàng)。
3.進(jìn)入編輯代碼塊的界面。

4.進(jìn)行代碼塊命名,我一般都是用My做前綴,后面是名稱,需要占位的代碼可以用特殊格式寫<#type#>。
5.最后點(diǎn)擊Done完成。
補(bǔ)充說明一下下面的幾個(gè)選項(xiàng):
1.Language:選擇開發(fā)語言。
2.Platform:可用于的平臺(tái)iOS、macOS、tvOS、watchOS。
3.Completion:和代碼塊的名稱要一樣,否則引用的時(shí)候打不出來。
4.Availabililty:在哪些地方可以調(diào)用出代碼塊,比如有的代碼塊適用于.h文件,有的代碼塊適用于.m文件,他們的代碼塊名稱很相似,為了引用的時(shí)候不都彈出來干擾選擇,可以設(shè)置這個(gè)選項(xiàng)。規(guī)定其可用范圍。
常用的自定義代碼塊:
屬性構(gòu)建:
@property (nonatomic, assign) <#Type#> <#name#>;
@property (nonatomic, copy) <#Type#> *<#name#>;
@property (nonatomic, strong) <#Type#> *<#name#>;
@property (nonatomic, weak) <#Type#> *<#name#>;
@property (nonatomic, copy) void (^<#name#>Block) (<#name#>);
強(qiáng)弱Self:
__weak __typeof(self) weakSelf = self;
__strong __typeof(self) strongSelf = weakSelf;
懶加載:
- (<#type#> *)<#name#> {
if (!_<#property#>) {
}
return _<#property#>;
}
單例:
static <#ClassSingle#> *_sharedSingleton = nil;
static dispatch_once_t _onceToken;
+ (instancetype)shareSingleton {
dispatch_once(&onceToken, ^{
if (_sharedSingleton == nil) {
_sharedSingleton = [[super allocWithZone:NULL] init];
}
});
return _sharedSingleton;
}
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
return [<#ClassSingle#> shareSingleton];
}
- (id)copyWithZone:(nullable NSZone *)zone {
return [<#ClassSingle#> shareSingleton];
}
- (id)mutableCopyWithZone:(nullable NSZone *)zone {
return [<#ClassSingle#> shareSingleton];
}
- (void)destorySingle {
_onceToken = 0;
_sharedSingleton = nil;
}
還有一些關(guān)于UI快速創(chuàng)建的,快速創(chuàng)建UILabel,UIButton,UITableView,UICollectionView等,一些快速構(gòu)建約束的,就不一一列舉了。
問題:
這時(shí)候的的人可能會(huì)問,我也想搞一套這個(gè)東西,但是我一個(gè)一個(gè)的往上粘也太麻煩了,有沒有直接把寫好的一套的代碼塊直接挪到項(xiàng)目中去呢?
這個(gè)還真有。首先,我們要知道存放代碼塊的文件在哪,找到這個(gè)文件,將現(xiàn)有的代碼塊文件,放進(jìn)這個(gè)文件夾中就可以了。在桌面(shift + command + G)復(fù)制下面的路徑回車。
文件路徑:
~/Library/Developer/Xcode/UserData/CodeSnippets
存放代碼塊的地址:
https://github.com/WarmLGZ/CodeSnippetsFile
總結(jié):
這個(gè)代碼塊確實(shí)能提升我們的代碼效率,別人剛寫個(gè)UILabel你的一塊代碼都寫完了,就是這么省事。還有一次我Xcode升級了以后,我之前自己定義的一些代碼塊就沒有了。寫這個(gè)文章也為了保存一份文件,以防萬一。還有哪些不足和需要補(bǔ)充的地方望大家補(bǔ)充指教,必虛心學(xué)習(xí)。