經驗之談—PCH 中使用:const 與宏
很多時候,由於開發的需要,我們常常需要在pch中定義一些在整個項目中都用得到的變數等 一般來說,在以前的開發過程中,我們都習慣於直接在pch中寫一個宏就搞定了。但是我們仔細的分析蘋果官方文檔,會發現,他裡面定義的一些變數,不是用宏定義的,而是用const 那我們就要知道為什麼用const了,首先瞭解一下const的一些基本的使用,在C語言的文法中,若我們若const休息一些變數會出現什麼情況,簡單瞭解一下,這也是面試常問的內容:
那麼就簡單的回顧一下吧:
修飾常量:
<code class=" hljs cs">void testConst(){ const int age1 = 20; int const age2 = 30;}</code>
當是這種情況的時候:效果是一樣的,這個時候 age1\age2是常量, 唯讀
當修飾指標的時候,分情況
就近原則 靠近誰 誰就相當於常量 不可重新賦值或者重新指向
<code class=" hljs cs">void testConst2(){ int age = 20; // const的修飾的*p1和*p2,*p1和*p2是常量,不能通過p1、p2指標間接修改其他變數的值 const int *p1 = &age; int const *p2 = &age; int num = 30; p1 = # p2 = # // const修飾的p3,p3是個常量,p3不能再指向其他變數 int * const p3 = &age; // 寫法錯誤 // int num = 30; // p3 = # // 寫法正確 // *p3 = 30;}</code>
const的修飾的*p1和*p2,*p1和*p2是常量,不能通過p1、p2指標間接修改其他變數的值
那麼我們在項目中,應該怎麼使用呢?
我們定義一個類 :比如這個類中是我們項目中的一些資料
ZYConst.h檔案中:
<code class=" hljs objectivec">#import <foundation foundation.h="">// 通知// 表情選中的通知extern NSString * const ZYEmotionDidSelectNotification;extern NSString * const ZYSelectEmotionKey;// 刪除文字的通知extern NSString * const ZYEmotionDidDeleteNotification;</foundation></code>
ZYConst.m中:
<code class=" hljs objectivec">#import <foundation foundation.h="">// 通知// 表情選中的通知NSString * const ZYEmotionDidSelectNotification = @"ZYEmotionDidSelectNotification";NSString * const ZYSelectEmotionKey = @"ZYSelectEmotionKey";// 刪除文字的通知NSString * const ZYEmotionDidDeleteNotification = @"ZYEmotionDidDeleteNotification";</foundation></code>
那我們在pch中,直接匯入這個ZYConst檔案就可以了
#import "ZYConst.h"
那麼整個項目中,就有了我們在這個類中定義的一些變數
好處:
使用const修飾的,在記憶體中就只有一份,那麼無論你在項目中的哪裡使用,都是這一份,所以強烈推薦使用 使用宏的話:宏是在編譯的時候 將我們定義的宏的內容,直接編譯成我們寫的字串,那麼可能存在多次建立,多次調用的。
注意
有些時候,const還是不能替代宏的,比如:
// RGB顏色#define ZYColor(r, g, b) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1.0]// 隨機色#define ZYRandomColor HWColor(arc4random_uniform(256), arc4random_uniform(256), arc4random_uniform(256))
這個時候,就不能使用const,因為const後面接的內容不能是通過一些計算出來的結果,而是一些死的東西。