【发布时间】:2015-01-15 09:17:48
【问题描述】:
我正在开发 IOS 静态库。 我需要创建只能在这个库中访问的全局变量。 我知道 3 种方法来做到这一点
问题是,哪种方式更好。
第一个解决方案:SharedInstance
.h:
@interface GlobalVars : NSObject
@property int counter;
+(instancetype)sharedInstance;
@end
.m:
@implementation GlobalVars
+(instancetype)sharedInstance {
static dispatch_once_t p = 0;
__strong static id _sharedObject = nil;
dispatch_once(&p, ^{
_sharedObject = [[self alloc] init];
});
return _sharedObject;
}
+(int)counter{
return [GlobalVars sharedInstance].counter;
}
+(void)setCounter:(int)_counter{
[GlobalVars sharedInstance].counter=_counter;
}
@end
在代码中使用:
[GlobalVars setCounter:5];
int i= GlobalVars.counter
第二种方案:静态变量+类方法
h:
@interface GlobalVars
+ (int) counter;
+ (void) setCounter:(int)val;
@end
米:
@implementation GlobalVars
static int value;
+ (int) counter {
return value;
}
+ (void) setCounter:(int)val {
value = val;
}
@end
在代码中使用:
[GlobalVars setCounter:5];
int i= GlobalVars.counter
第三种解决方案:外部变量
常量.h:
extern int *kCounter ;
在代码中使用:
#import "Constants.h"
-(void)someMethod{
kCounter=5;
int i=kCounter;
}
谢谢
编辑: 解决方案必须是“线程安全的”
【问题讨论】:
标签: ios objective-c iphone xcode global-variables