iPhone开发全局变量的使用
2011-08-24 12:23
537 查看
在iPhone开发中,使用全局变量有这么几种实现方法:
1、在AppDelegate中声明并初始化全局变量
然后在需要使用该变量的地方插入如下的代码:
//取得AppDelegate,在iOS中,AppDelegat被设计成了单例模式
xxxAppDelegate *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
extern int count;
count = 0;//非指针类型
2.5 使用全局变量:和使用普通变量一样使用。
3、单例的全局访问方法:
@interface MySingleton : NSObject
{
⇒① NSString *testGlobal;
}
+ (MySingleton *)sharedSingleton;
⇒②@property (nonxxxx,retain) NSString *testGlobal;
@end
@implementation MySingleton
⇒③@synthesize testGlobal;
+ (MySingleton *)sharedSingleton
{
static MySingleton *sharedSingleton;
@synchronized(self)
{
if (!sharedSingleton)
sharedSingleton = [[MySingleton alloc] init];
return sharedSingleton;
}
}
@end
把①、②、③的地方换成你想要的东西,
使用例:
[MySingleton sharedSingleton].testGlobal = @"test";
1、在AppDelegate中声明并初始化全局变量
然后在需要使用该变量的地方插入如下的代码:
//取得AppDelegate,在iOS中,AppDelegat被设计成了单例模式
xxxAppDelegate *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
extern int count;
count = 0;//非指针类型
2.5 使用全局变量:和使用普通变量一样使用。
3、单例的全局访问方法:
@interface MySingleton : NSObject
{
⇒① NSString *testGlobal;
}
+ (MySingleton *)sharedSingleton;
⇒②@property (nonxxxx,retain) NSString *testGlobal;
@end
@implementation MySingleton
⇒③@synthesize testGlobal;
+ (MySingleton *)sharedSingleton
{
static MySingleton *sharedSingleton;
@synchronized(self)
{
if (!sharedSingleton)
sharedSingleton = [[MySingleton alloc] init];
return sharedSingleton;
}
}
@end
把①、②、③的地方换成你想要的东西,
使用例:
[MySingleton sharedSingleton].testGlobal = @"test";
相关文章推荐
- 在 iPhone 开发中,全局变量的几种使用方法
- 在iPhone开发中,使用全局变量
- 在iPhone开发中,全局变量的几种使用方法
- iPhone开发之全局变量的使用
- iPhone开发之全局变量的使用(转)
- 在iPhone开发中,全局变量的几种使用方法
- 在iPhone开发中,全局变量的几种使用方法
- 在iPhone开发中,全局变量的几种使用方法
- iPhone开发之全局变量的使用
- 在iPhone开发中,全局变量的几种使用方法
- iPhone开发之全局变量的使用
- iPhone开发之全局变量的使用
- IPHONE开发 全局变量的声明和使用
- 为何Android开发中不推荐使用全局变量传参
- iphone 声明和使用全局变量
- Linux开发心得总结20 - 内核编程中的全局变量使用(EXPORT_SYMBOL())
- DT二次开发之-常量全局变量说明及使用
- android开发必备知识:ndroid使用全局变量
- Android开发--全局类的实现(用于保存使用的全局变量)
- ios开发中全局变量的使用