我想要一个 NSMutableDictionary
可以从网络中提取数据,并且可以从应用程序中的任何 View Controller 获得。
换句话说,我应该能够在应用程序的任何部分获取和设置该 dictionary
中的信息。
我已经阅读了几种解决方案,其中之一是创建一个包含该字典的 .h 文件,然后将该 .h 文件添加到 .pch 中,这样它就可以在任何地方使用。
第二个选项是在 AppDelegate
中创建字典,但是人们说这是一个糟糕的解决方案。
请告知最好的方法。谢谢!
最佳答案
您可以使用单例类来共享数据
检查这个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;
}
你可以像这样从任何地方访问你的字典
[MyManager sharedManager].dict
关于iphone - 创建 NSMutableDictionary,它可以在应用程序的任何地方使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14831505/