几种全局变量的使用方法
2016-07-20 16:29
1016 查看
在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”;
Demo下载地址:http://download.csdn.net/detail/p709723778/5159342
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”;
Demo下载地址:http://download.csdn.net/detail/p709723778/5159342
相关文章推荐
- Lua中的全局变量、非全局变量总结
- js DOM 元素ID就是全局变量
- c语言全局变量和局部变量问题及解决汇总
- 深入探讨C语言中局部变量与全局变量在内存中的存放位置
- 深入uCOS中全局变量的使用详解
- Ruby 中$开头的全局变量、内部变量、隐藏变量介绍
- 全局变量与局部变量在内存中的区别详细解析
- PHP全局变量与超级全局变量区别分析
- 关于全局变量和局部变量的那些事
- javascript中局部变量和全局变量的区别详解
- javascript 用局部变量来代替全局变量第1/2页
- 浅谈JavaScript的全局变量与局部变量
- 探讨JavaScript中声明全局变量三种方式的异同
- 解析在PHP中使用全局变量的几种方法
- JQuery中使用Ajax赋值给全局变量失败异常的解决方法
- 理运用命名空间让js不产生冲突避免全局变量的泛滥
- 解析 ruby 全局变量
- PHP中全局变量global和$GLOBALS[]的区别分析
- php 获取全局变量的代码
- PHP Global定义全局变量使用说明