0

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!

Rajneesh071
  • 30,846
  • 15
  • 61
  • 74
Sergey Katranuk
  • 1,162
  • 1
  • 13
  • 23

2 Answers2

4

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
Anil Varghese
  • 42,757
  • 9
  • 93
  • 110
  • This sounds interesting, but since I'm still a newbie, it sounds too complicated for now. Is there a more in depth tutorial for this, that you could recommend? – Sergey Katranuk Feb 12 '13 at 11:53
  • 1
    [This will help you](http://klanguedoc.hubpages.com/hub/iOS-5-How-To-Share-Data-Between-View-Controllers-using-a-Singleton) – Vinayak Kini Feb 12 '13 at 11:59
  • @Anil Thanks for the example and code. I accept your answer for now, and will try to use it in my app. But I'm sure I'll be back with questions :) – Sergey Katranuk Feb 12 '13 at 12:04
  • @SergeyCatraniuc Welcome..:) [Check this](http://www.galloway.me.uk/tutorials/singleton-classes/) for the detail implementation – Anil Varghese Feb 12 '13 at 12:14
-1

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];
Mouhamad Lamaa
  • 884
  • 2
  • 12
  • 26