创建可在应用程序的任何位置使用的NSMutableDictionary [英] Create NSMutableDictionary that will be available from everywhere in the app
问题描述
我希望有一个 NSMutableDictionary
,它将从网上提取数据,并且可以从应用中的任何视图控制器获得。
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.
我已经阅读了几个解决方案,一个是创建一个包含该字典的.h文件,然后将.h文件添加到.pch中它将随处可用。
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.
第二个选项是在 AppDelegate
中创建dict,但人们说这是一个糟糕的解决方案。
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!
推荐答案
您可以使用单例类共享数据
选中此单身人士课程
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
这篇关于创建可在应用程序的任何位置使用的NSMutableDictionary的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!