在某個(gè)類中聲明一個(gè)static 靜態(tài)變量, 其他類中想使用它或者修改它不用new 這個(gè)對(duì)象 ,直接使用它的類名方可直接拿到這個(gè)靜態(tài)變量的對(duì)象,便可以在其他類中任意修改這個(gè)變量的數(shù)值。
static靜態(tài)變量在其他類中是不能通過類名直接訪問的,它的作用域只能是在聲明的這個(gè).m文件中 。不過可以調(diào)用這個(gè)類的方法間接的修改這個(gè)靜態(tài)變量的值。
MyClass.h
警告:??static 寫在interface外面編譯是沒有錯(cuò)誤的,但是編譯器會(huì)報(bào)警告,這么說這樣的寫法是不被編輯器認(rèn)可的。
錯(cuò)誤:static 寫在interface里面會(huì)直接報(bào)錯(cuò),顯然這樣的語法是不被認(rèn)可的。
+(void) addCount;??各位盆友們注意一下這法方法前面的+號(hào)。 它的意思是標(biāo)致這個(gè)方法為靜態(tài)方法,標(biāo)志+號(hào)后不用創(chuàng)建這個(gè)對(duì)象通過類名可以直接調(diào)用這個(gè)靜態(tài)方法。 而之前方法前用過的-號(hào),標(biāo)志-號(hào)后的方法必須通過本類的對(duì)象或者在本來中才可以使用。
[objc]view plaincopy
#import?
//警告
//static?int?sCount?;
@interfaceMyClass?:?NSObject
{
//錯(cuò)誤的寫法
//static?int?sCount;
}
+(void)?addCount;
@end
MyClass.m
static關(guān)鍵字聲明的變量必須放在implementation外面,或者方法中,如果不為它賦值默認(rèn)為0,它只在程序開機(jī)初始化一次。
+(void)addCount 因?yàn)闃?biāo)識(shí)了+號(hào),所以這個(gè)方法無需使用這個(gè)類的對(duì)象調(diào)用。直接使用類名方可調(diào)用這個(gè)方法。
[objc]view plaincopy
#import?"MyClass.h"
staticintsCount??=100;
@implementationMyClass
+(void)addCount
{
sCount?++;
NSLog(@"靜態(tài)整型變量的值為:%d",?sCount);
}
@end
main.m
無需alloc這個(gè)對(duì)象,直接使用MyClass類名方可直接調(diào)用addCount方法。
[objc]view plaincopy
#import?"MyClass.h"
intmain(intargc,charchar*argv[])
{
NSAutoreleasePool*pool?=?[[NSAutoreleasePoolalloc]init];
//添加我們的測(cè)試代碼
[MyClassaddCount];
intretVal?=?UIApplicationMain(argc,?argv,nil,nil);
[poolrelease];
returnretVal;
}
運(yùn)行這個(gè)程序,初始化賦值為100 ,調(diào)用方法的時(shí)候++,所以打印出來的數(shù)值為101。
MyClass.m
將static整型變量定義在方法中,并且為其賦值100。
#import "MyClass.h"
@implementation MyClass
+(void)addCount
{
static int sCount??= 100;
sCount ++;
NSLog(@"靜態(tài)整型變量的值為:%d", sCount);
}
@end
main.m
循環(huán)5次調(diào)用這個(gè)方法,看看結(jié)果是什么樣字,結(jié)果肯定是101吧。。
#import
#import "MyClass.h"
int main(int argc, char *argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
//添加我們的測(cè)試代碼
for (int i =0; i < 5; i++) {
[MyClass addCount];
}
int retVal = UIApplicationMain(argc, argv, nil, nil);
[pool release];
return retVal;
}

程序員不要相信任何人說的任何有關(guān)程序的話,一定相信自己,相信自己眼睛看到的一切,哇咔咔~~
可見即使將static靜態(tài)變量寫在方法中,
它的初始化也是在程序開機(jī)時(shí),程序一旦啟動(dòng)以后static是不能在創(chuàng)建的。
所以程序在這里調(diào)用了5次這個(gè)方法,sCount的值并沒有因?yàn)橹匦聞?chuàng)建static sCount而改變,而是將sCount的值一直存在內(nèi)存中。