单例模式
来源:互联网 发布:零售行业数据分析 书 编辑:程序博客网 时间:2024/04/27 15:34
转载:http://blog.csdn.net/joiningss/article/details/6714234
在iPhone开发中,使用全局变量有这么几种实现方法:
1、在AppDelegate中声明并初始化全局变量
然后在需要使用该变量的地方插入如下的代码:
//取得AppDelegate,在iOS中,AppDelegat被设计成了单例模式
xxxAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
appDelegate.Your Variable
2、使用 extern 关键字
2.1 新建Constants.h文件(文件名根据需要自己取),用于存放全局变量;
2.2 在Constants.h中写入你需要的全局变量名,例如:
int count;//非指针类型
注意:在定义全局变量的时候不能初始化,否则会报错!
2.3 在需要用到全局变量的文件中引入此文件:
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";
- 单例、单例模式
- 单例模式-多线程单例模式
- 单件模式(单例模式)
- 设计模式------单例模式
- 设计模式------单例模式
- 设计模式-单例模式
- 设计模式 - 单例模式
- 设计模式---单例模式
- 设计模式---单例模式
- PHP模式-单例模式
- 【设计模式】单例模式
- 设计模式-单例模式
- 设计模式----单例模式
- 设计模式--单例模式
- 设计模式-单例模式
- 单例模式(单子模式)
- 设计模式-单例模式
- [设计模式] 单例模式
- 应用程序和数据库连接
- ASP.NET编程模型之ASP.NET页面生命周期图解
- mmap做映像和直接进行IO的效率比较
- Win7+IE8如何使用VS2005调试问题
- png转化为gif
- 单例模式
- jquery easy ui 框架
- java学习心得
- spring 事务管理
- DELL R710安装CentOS 6.2
- Mybatis 动态SQL
- 正则表达式教程
- POJ3760
- Linux中的log介绍(二)--Syslogd