我创建了一个包含多个视图的小应用。为此,我使用故事板,并为每个视图一个viewcontroller。现在,我必须存储用户可以在视图上输入的数据。我想为此使用字典。我现在,如何创建字典:
NSMutableDictionary *globalData = [[NSMutableDictionary alloc] init];
//add keyed data
[globalData setObject:@"Object One" forKey:@"1"];
[globalData setObject:@"Object Two" forKey:@"2"];
我现在正在搜索添加和实例化此词典的正确位置,它可以在所有视图中用作模型。
答案 0 :(得分:1)
您可以使用单例模型对象来保留全局数据。如果您在* .pch文件中声明几乎所有viewControllers中使用它。如果您使用字典,则可以定义一些常量以便于使用。
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;
}
答案 1 :(得分:0)
...
-(NSMutbaleDictionary *) globalData{
if (_globalData == nil){
_globalData = [[NSMutableDictionary alloc]init];
}
return _globalData;
}