创建可在应用程序的任何位置使用的NSMutableDictionary
我希望有一个NSMutableDictionary
,它将从Web中提取数据,并且可以从应用程序中的任何视图控制器获得。
换句话说,我应该能够在应用程序的任何部分中获取和设置该dictionary
中的信息。
我已经阅读了几个解决方案,一个是创建一个包含该字典的.h文件,然后将该.h文件添加到.pch中,以便它可以在任何地方使用。
第二种选择是在AppDelegate
创建dict,但人们说这是一个糟糕的解决方案。
请告知最好的方法。 谢谢!
您可以使用singleton类来共享数据
检查这个Singleton类
MyManger.h
#import @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; }
您可以像这样从任何地方访问您的字典
[MyManager sharedManager].dict
您可以在应用程序委托中创建它并设置其setter和getter。 每次需要访问它时,您都可以创建主代理的实例
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];