說明 | 時間 |
---|---|
首次發布 | 2019年04月03日 |
最近更新 | 2019年04月09日 |
static
- 1、修飾局部變量的時候,該局部變量只會 初始化一次,且 內存中的地址不變,和 延長局部變量的生命周期。
- (void)viewDidLoad {
[super viewDidLoad];
static NSInteger count = 0;
count++;
NSLog(@"打印:%ld, 地址:%p", count, &count);
}
輸出如下(忽略部分無用內容):
2019-04-03 打印:1, 地址:0x1021d1510
2019-04-03 <FourthViewController: 0x7ffd716082d0>釋放了
2019-04-03 打印:2, 地址:0x1021d1510
2019-04-03 <FourthViewController: 0x7ffd71403eb0>釋放了
2019-04-03 打印:3, 地址:0x1021d1510
2019-04-03 <FourthViewController: 0x7ffd7530d200>釋放了
- 2、使全局變量的作用域只限定在本類里(默認情況下,全局變量在整個程序中是可以被訪問,即:全局變量的作用域是整個項目文件)。
extern:訪問全局變量,只需要定義一份全局變量,多個文件共享,與 const
一塊使用。
一般使用場景:寫一個全局變量的類 GlobalConst,GlobalConst.h
聲明,GlobalConst.m
賦值。如:
// GlobalConst.h
#import <Foundation/Foundation.h>
extern NSString *const noticeName;
// GlobalConst.m
#import "GlobalConst.h"
NSString *const noticeName = @"noticeName";
如系統的方式:
// .h
UIKIT_EXTERN NSNotificationName const UIApplicationDidFinishLaunchingNotification;
UIKIT_EXTERN NSNotificationName const UIApplicationDidBecomeActiveNotification;
UIKIT_EXTERN NSNotificationName const UIApplicationWillResignActiveNotification;
const
- 1、修飾基本數據類型:
const int
和int const
是一樣的。編譯器都認為是int const
類型。
const int count = 10;
int const num = 20;
// count = 10; //Cannot assign to variable 'count' with const-qualified type 'const int'
// num = 20; //Cannot assign to variable 'num' with const-qualified type 'const int'
- 2、修飾指針類型: 星號以及星號之后的內容,只修飾右側的一個變量。
NSString *const a = @"a";
// a = @"b"; // ? Cannot assign to variable 'a' with const-qualified type 'NSString *const __strong'
const NSString *b = @"b";
// *b 不可變,Read-only variable is not assignable
b = @"c";
NSString const *c = @"c";
c = @"dd";