作為預處理指令,#pragma 在編譯時進行計算。但它并不像如#ifdef…#endif之類的宏,#pragma 的使用方式不會改變你的應(yīng)用運行時的行為。相反的,#pragma 聲明主要由 Xcode 用來完成兩個主要任務(wù):整理代碼和防止編譯器警告。
一、整理代碼
相信大家都用過 #pragma mark來在劃分代碼模塊,使代碼更整潔、邏輯更清晰。例如:
@implementation ViewController
- (id)init {
...
}
#pragma mark - UIViewController
- (void)viewDidLoad {
...
}
#pragma mark - IBAction
- (IBAction)cancel:(id)sender {
...
}
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
...
}
#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
...
}
二、防止編譯器警告
用#pragma聲明來防止來自編譯器或者靜態(tài)分析器的警告是我們平時比較少用的。使用的姿勢是這樣的:
// clang診斷push
#pragma clang diagnostic push
#pragma clang diagnostic 操作 "操作具體類型"
// clang診斷pop,如果不pop,下面寫的代碼,也會將undeclared selector識別為error
#pragma clang diagnostic pop
- 用法1: 將警告識別為錯誤
執(zhí)行一些未實現(xiàn)的方法時, 避免出現(xiàn)unrecognized selector sent to instance 0x..., 通過error操作中的'-Wundeclared-selector'(找不到方法)將原始的警告變?yōu)殄e誤:
1.1 方法未實現(xiàn)警告
1.2 方法未實現(xiàn)警告變錯誤
1.3 方法實現(xiàn)后錯誤消失
- 用法2: 忽略警告
同樣對于1.1 方法未實現(xiàn)警告的處理也可以采用ignored忽略操作解除警告,但是未實現(xiàn)方法的情況下運行還是會崩潰, 此處只做使用說明:
ignored 忽略1.1的方法未實現(xiàn)警告
- 用法3: 忽略參數(shù)非空檢查
當一些參數(shù)出現(xiàn)可為空、不可為空時的錯誤警告可以通過ignored操作的'-Wnonnull'(忽略非空參數(shù)檢查)來解除:
3.1 參數(shù)不為空時, 傳遞了nil之后的警告
3.2 忽略警告
實際上,clang diagnostic并不只有上面的兩種固定用法
error:警告識別為錯誤`
ignored:忽略警告
還有很多其他的, 當然具體的操作類型也有很多, 比如常用的有:
-Warc-performSelector-leaks performSelector可能導致內(nèi)存泄露
-Wundeclared-selector 找不到方法
-Wdeprecated-declarations 廢棄的方法
-Wincompatible-pointer-types 指針類型不匹配
-Warc-retain-cycles Block的循環(huán)引用
-Wunused-variable 未使用的變量
進階的話進去看看Clang 的git 文檔
結(jié)語
路漫漫其修遠兮,吾將上下而求索~
.End





