Sergey Katranuk
Sergey Katranuk

Reputation: 1182

Create NSMutableDictionary that will be available from everywhere in the app

I want to have a NSMutableDictionary that will pull it's data from the web, and will be available from any view controller in the app.

In other words, I should be able to get and set the info in that dictionary in any part of the app.

I've read several solutions to this, one being to create an .h file that will contain that dictionary, and then add that .h file to the .pch so it will be available anywhere.

And the second option was to create the dict in AppDelegate, however people said it's a bad solution.

Please advise on the best way to do this. Thanks!

Upvotes: 0

Views: 454

Answers (2)

Anil Varghese
Anil Varghese

Reputation: 42977

You can use singleton class for sharing the data
Check this Singleton class

MyManger.h

#import <foundation/Foundation.h>

@interface MyManager : NSObject {
NSMutableDictionary *_dict
}

@property (nonatomic, retain) NSMutableDictionary *dict;

 + (id)sharedManager;  
@end 

MyManger.m

#import "MyManager.h"

static MyManager *sharedMyManager = nil;

 @implementation MyManager

 @synthesize dict = _dict;

#pragma mark Singleton Methods  

+ (id)sharedManager {
 @synchronized(self) {
    if(sharedMyManager == nil)
      sharedMyManager = [[super allocWithZone:NULL] init];
 }
return sharedMyManager;
} 

- (id)init {
   if (self = [super init]) {
  dict = [[NSMutableDictionary alloc] init];
   }
 return self;
}   

You can access your dictionary from everywhere like this

   [MyManager sharedManager].dict

Upvotes: 4

Mouhamad Lamaa
Mouhamad Lamaa

Reputation: 884

you can create it in the app delegate and set its setters and getters. and each time you need to acces it you can make and instance of the main delegate

AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];

Upvotes: -1

Related Questions