BennoDual
BennoDual

Reputation: 6259

using dictionary as model

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

Answers (2)

Anupdas
Anupdas

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

John
John

Reputation: 2694

  1. Declare the NSMutableDictionary as a property in .h file for all ViewControllers concerning the model
  2. In your .m file, implement the getter of the NSMutableDictionary using lazy instantiation.

..

-(NSMutbaleDictionary *) globalData{

    if (_globalData == nil){
        _globalData = [[NSMutableDictionary alloc]init]; 

    }

    return _globalData;   
}
  1. transfer the dictionary to other viewControllers of other views in prepareForSegue:

Upvotes: 0

Related Questions