經驗之談—PCH 中使用:const 與宏

來源:互聯網
上載者:User

經驗之談—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後面接的內容不能是通過一些計算出來的結果,而是一些死的東西。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.