標籤:
詳解Objective-C中靜態變數使用方法
Objective-C中
靜態變數使用方法是本文要介紹的內容,
Objective-C 支援全域
變數,主要有兩種實現方式:第一種和C/C++中的一樣,使用"extern"關鍵詞;另外一種就是使用單例實現。(比如我們經常會把一個
變數放在AppDelegate裡面作為全域
變數來訪問,其中AppDelegate就是一個單例類)
在Objective-C中如何?像C++中那樣的靜態成員變數呢?
你需要做的是在一個類A的implementation(.m或者.mm)檔案中定義一個static變數,然後為A類定義靜態成員函數(class method,也就是類方法)來操作該變數。這樣在其它類中你就不需要建立A類的執行個體來對static變數進行訪問。雖然該static變數並不是A類的靜態成員變數,但是也算達到了同樣的效果。static變數的範圍被限制在單一的檔案中。代碼可以如下所示:
- //example.h
- @interface Example : NSObject {
-
- }
-
- - (id)init;
- +(int)instanceCount;
-
- @end
-
- //example.m
- #import "example.h"
-
- static int count;
-
- @implementation Example
- -(id)init{
- self = [super init];
- if(nil!=self){
- count+=1;
- }
- return self;
- }
-
- +(int)instanceCount{
- return count;
- }
-
- @end
- //example.h
- @interface Example : NSObject {
-
- }
-
- - (id)init;
- +(int)instanceCount;
-
- @end
-
-
- //example.m
- #import "example.h"
-
- static int count;
-
- @implementation Example
- -(id)init{
- self = [super init];
- if(nil!=self){
- count+=1;
- }
- return self;
- }
-
- +(int)instanceCount{
- return count;
- }
- @end
上面的例子中你就可以通過[Example instanceCount]對靜態變數count進行訪問,無須建立執行個體。
Objective-C 靜態變數 使用方法