Objective-C中,在變量聲明前加上關鍵字static,可以使局部變量保留多次調用一個方法所得的值。例如下面的一句Objective-C語句:
static int hitCount = 0;
聲明整數hitCount是一個static靜態變量。和其他常見局部變量不同,Objective-C中的static靜態變量的初始值為0,所以前面顯示的初始化是多余的。此外,它們只在程序開始執行時初始化一次,並且在多次調用方法時保存這些數值。所以編碼序列
1
2
3
4
5
6
7
|
-(
void
) showPage
{
static
int
pageCount = 0;
...
++pageCount;
...
}
|
可能出現在一個showPage方法中,它用於記錄該方法的調用次數(在這種情況下,還可能是要打印的頁數)。只在程序開始時局部static靜態變最設置為0,並且在連續調用showPage方法時獲得新值。
注意,將pagaCnunt設置為局部靜態變量和實例變量之間的區別。對於前一種情況,pageCount能記錄調用showPage方法的所有對象打印頁面的數目。對后一種情況,pageCount變量可以計算每個對象打印的頁面數目,因為每個對象都有自己的pageCount副本。
記住只能在定義靜態和局部變量的方法中訪問這些變量。所以,即使靜態變量pageCount,也只能在pageCount函數中訪問。可以將變量的聲明移到所有方法聲明的外部(通常放在implementation文件的開始處),這樣所有方法都可以訪問它們,如:
1
2
3
4
5
|
#import “Printer.h”
static
int
pageCount;
@implementation Printer
...
@end
|
現在,該文件中包含的所有實例或者類方法都可以訪問變量pageCount。返回關於分數的討論,將reduce方法的代碼結合到實現文件Fraction.m中。不要忘了在接口文件Fraction.h中聲明reduce方法,之后,就可以在下面代碼中測試這個新方法。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
#import “Fraction.h”
int
main (
int
argc,
char
*argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Fraction *aFraction = [[Fraction alloc] init];
Fraction *bFraction = [[Fraction alloc] init];
[aFraction setTo: 1 over: 4];
// set 1st fraction to 1/4
[bFraction setTo: 1 over: 2];
// set 2nd fraction to 1/2
[aFraction print];
NSLog (@”+”);
[bFraction print];
NSLog (@”=”);
[aFraction add: bFraction];
// reduce the result of the addition and print the result
[aFraction reduce];
[aFraction print];
[aFraction release];
[bFraction release];
[pool drain];
return
0;
}
|
結果輸出如下:
1
2
3
4
5
|
1
/4
+
1
/2
=
3
/4
|
好了,Objective-C中static靜態變量的用法就介紹到這里,希望對初學者帶來幫助,謝謝閱讀。