在iPhone開發中,使用全局變量有這么幾種實現方法:
1、 在AppDelegate中聲明並初始化全局變量
然后在需要使用該變量的地方插入如下的代碼:
//取得AppDelegate,在iOS中,AppDelegat被設計成了單例模式
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
appDelegate.Your Variable
2、使用 extern 關鍵字
2.1 新建Constants.h文件(文件名根據需要自己取),用於存放全局變量;
2.2 在Constants.h中寫入你需要的全局變量名,
例如: NSString *url;//指針類型
int count;//非指針類型
注意:在定義全局變量的時候不能初始化,否則會報錯!
2.3 在需要用到全局變量的文件中引入此文件:
#import "Constants.h"
2.4 給全局變量初始化或者賦值:
extern NSString *url;
url = [[NSString alloc] initWithFormat:@"http://www.google.com"];
//指針類型;需要alloc(我試過直接 url = @"www.google.com" 好像也能訪問 )
extern int count;
count = 0;//非指針類型
2.5 使用全局變量:和使用普通變量一樣使用。