iT邦幫忙

2021 iThome 鐵人賽

DAY 3
0
自我挑戰組

iOS 菜鳥工程師的30天 objective-C系列 第 3

Day 03 - 關於 const, static, extern 的三兩事

#前言

由於前一篇使用了constextern,但對這兩者還不太了解,於是又去看了其他人的文章,試圖弄懂一點,就有了這篇~


#const

主要作用:

  1. 修飾 const 右邊的基本變數或指標變數
  2. 被修飾的變數只能讀,不能被修改 ⇒ 也就是常量,就像是Swift 的 let

下面舉個簡單例子:

//定義一個類型為int的變數a,初始值為10,const用來修飾a,因此a只可讀,不可修改
int const a = 10;

a = 20; // error

const int a = 10; //跟前者等價

再來透過 *p 和 p 來理解 const 的用法:

int const *p  // *p只可讀 ; p變數

int * const p // *p變數 ; p只可讀

const int * const p // p和*p都只可讀

int const * const p // p和*p都只可讀

#static

先來看個簡單的小例子:

-(void) noStatic {
    
    int a = 0;
    
    a++;
    
    NSLog(@"a = %d",a);
}

然後 viewDidLoad 執行5次

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self noStatic];
    [self noStatic];
    [self noStatic];
    [self noStatic];
    [self noStatic];
}

結果:

2021-09-17 11:02:30.057137+0800 TestOC[71225:1637744] a = 1
2021-09-17 11:02:30.057301+0800 TestOC[71225:1637744] a = 1
2021-09-17 11:02:30.057429+0800 TestOC[71225:1637744] a = 1
2021-09-17 11:02:30.057541+0800 TestOC[71225:1637744] a = 1
2021-09-17 11:02:30.057633+0800 TestOC[71225:1637744] a = 1

可以發現到每次執行 noStatic 時,a 都是全新的變數,系統分配不同的記憶體位址給 a,因此 a 都是 1。

那如果加上 static 呢?

-(void) haveStatic {
    
    static int a = 0;
    
    a++;
    
    NSLog(@"a = %d",a);
}

@end

一樣執行 5 次,來看結果

2021-09-17 11:07:10.027838+0800 TestOC[71247:1640410] a = 1
2021-09-17 11:07:10.027932+0800 TestOC[71247:1640410] a = 2
2021-09-17 11:07:10.027995+0800 TestOC[71247:1640410] a = 3
2021-09-17 11:07:10.028055+0800 TestOC[71247:1640410] a = 4
2021-09-17 11:07:10.028122+0800 TestOC[71247:1640410] a = 5

a值改變了,也意味著每次對 a 變數做存取時,系統都在同一個的記憶體位址做操作,因此 a 值才會越來越多。同時也代表 a 只初始化一次,一份記憶體位置。


#extern

主要作用是宣告外部全域性變數,注意!extern 只能宣告,不能用於實現。
在開發中,常單獨使用一個類來管理全域變數或常量。
我們可以在.h檔中 extern宣告全域變數

//宣告全域變數
extern NSString * const name;
extern NSInteger const count;

然後在 .m檔中去實現

#import <Foundation/Foundation.h>
//實現
NSString * const name = @"tom";
NSInteger const count = 3;

這樣只要匯入標頭檔案,就可以使用全域變數。


#參考資料

http://xcodertw.blogspot.com/2013/08/objective-c-static.html
https://codertw.com/ios/326890/


上一篇
Day 02 - Variables 與 Constants
下一篇
Day 04 - 循環(Loops)
系列文
iOS 菜鳥工程師的30天 objective-C10
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言