IOS项目中使用全局变量


 1 //
 2 //  GlobalVar.h
 3 //
 4 
 5 #import <Foundation/Foundation.h>
 6 
 7 @interface GlobalVar : NSObject{
 8     NSString * strTest;
 9 }
10 @property(strong,nonatomic)NSString * strTest;
11 +(GlobalVar *)sharedGlobalVar;
12 
13 @end

 1 //
 2 //  GlobalVar.m
 3 //
 4 
 5 #import "GlobalVar.h"
 6 
 7 @implementation GlobalVar
 8 @synthesize strTest;
 9 
10 +(GlobalVar *)sharedGlobalVar{
11     static GlobalVar * globalVar;
12     @synchronized(self){//线程锁,防止数据呗多线程操作
13         if (!globalVar) {
14             globalVar=[[GlobalVar alloc]init];
15         }
16         return globalVar;
17     }
18 }
19 
20 -(id)init{
21     if (self=[super init]) {
22         strTest=@"原始字符串";
23     }
24     return self;
25 }
26 
27 @end

在另一界面添加两个button,增加测试方法

 1 -(void)btnTest:(id)sender{
 2     NSString * strTest=[GlobalVar sharedGlobalVar].strTest;
 3     NSLog(@"%@",strTest);
 4     [GlobalVar sharedGlobalVar].strTest=@"第一次修改";
 5 }
 6 -(void)btnTest1:(id)sender{
 7     NSString * strTest=[GlobalVar sharedGlobalVar].strTest;
 8     NSLog(@"%@",strTest);
 9     [GlobalVar sharedGlobalVar].strTest=@"第二次修改";
10 }

按顺序触发btnTest和btnTest1方法各两次,输出结果如下

2013-07-12 16:16:19.342 candr.alipay[25540:11303] 原始字符串
2013-07-12 16:16:20.028 candr.alipay[25540:11303] 第一次修改
2013-07-12 16:16:20.975 candr.alipay[25540:11303] 第一次修改
2013-07-12 16:16:24.628 candr.alipay[25540:11303] 第二次修改

最后一次点击时设置断点将测试字符串po出

(lldb) po [GlobalVar sharedGlobalVar].strTest
$0 = 0x0000bdac 第二次修改
(lldb) 

验证正确,完毕

原文地址:https://www.cnblogs.com/candr/p/3186539.html