您可以使用单例模型对象来保存全局数据。如果您在几乎所有视图控制器中都使用它,请在 *.pch 文件中声明。如果您使用字典,则定义一些常量以便于使用。
GlobalDataModel *model = [GlobalDataModel sharedDataModel];
//Pust some value
model.infoDictionary[@"StoredValue"] = @"SomeValue";
//read from some where else
NSString *value = model.infoDictionary[@"StoredValue"];
.h 文件
@interface GlobalDataModel : NSObject
@property (nonatomic, strong) NSMutableDictionary *infoDictionary;
+ (id)sharedDataModel;
@end
.m 文件
@implementation GlobalDataModel
static GlobalDataModel *sharedInstance = nil;
- (id)init{
self = [super init];
if (self) {
self.infoDictionary = [NSMutableDictionary dictionary];
}
return self;
}
+ (id )sharedDataModel {
if (nil != sharedInstance) {
return sharedInstance;
}
static dispatch_once_t pred; // Lock
dispatch_once(&pred, ^{ // This code is called at most once per app
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}