Reputation: 6259
I have created a small app with several views. For this I use the storyboard and for each view a viewcontroller. Now, I have to store data, which the user can enter on the view. I want to use a Dictionary for this. I now, how to create a dictionary:
NSMutableDictionary *globalData = [[NSMutableDictionary alloc] init];
//add keyed data
[globalData setObject:@"Object One" forKey:@"1"];
[globalData setObject:@"Object Two" forKey:@"2"];
I am searching now the right place to add and instantiate this dictionary, that it can be used as model in all views.
Upvotes: 0
Views: 409
Reputation: 10201
You can use a singleton model object to keep the global data. If you are using this in almost all viewControllers declare in *.pch file. If you are using dictionary you define some constants for ease of use.
GlobalDataModel *model = [GlobalDataModel sharedDataModel];
//Pust some value
model.infoDictionary[@"StoredValue"] = @"SomeValue";
//read from some where else
NSString *value = model.infoDictionary[@"StoredValue"];
.h file
@interface GlobalDataModel : NSObject
@property (nonatomic, strong) NSMutableDictionary *infoDictionary;
+ (id)sharedDataModel;
@end
.m file
@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;
}
Upvotes: 1
Reputation: 2694
..
-(NSMutbaleDictionary *) globalData{
if (_globalData == nil){
_globalData = [[NSMutableDictionary alloc]init];
}
return _globalData;
}
Upvotes: 0