前一陣子,做項目的時候到網上找Demo,打開運行的時候發現其中變量前有關鍵字extern和static,所以我研究了一下子
對於extern來說可以理解為擴展吧是這樣的是從一個類擴展到另一個類中的
在SplashViewController.m中定義一個變量是這樣的
#import "SplashViewController.h"
NSString* meString=@"123";
@implementation SplashViewController
// NSString* meString=@"123";
.................
這兩 個地方都行
如果在另外的類iTennisViewController.m中要用到這個類中的meString時只需在iTennisViewController.m中寫成這樣
#import "iTennisViewController.h"
extern NSString* meString;
@implementation iTennisViewController
即可
這樣你在iTennisViewController.m中直接打印meString,你會發現 是123,當然你也可以對meString重新斌值 ,就是說meString雖然定義在SplashViewController.m中但好像是公共的,也稱為全局變量吧
對於static修飾的變量
#import "SecondViewController.h"
static int count;
@implementation SecondViewController;
.......
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
NSLog(@"viewWillAppear is %d",count);
count+=1;
}
這樣你每進入一次界面就會發現count加1
除非程序完全退出重啟,count才會清除,objective-c中用static修飾的變量和java中的靜態變量是有區別的,其不能通過類名直接訪問,當然你想直接訪問也是能實現的在.m中寫一個類方法反回count就行了,而且其作用域是其本類,不能擴展到其他類中
今天就寫到這了
請大家多多指教