gpt4 book ai didi

ios - 使用字典作为模型

转载 作者:行者123 更新时间:2023-11-29 03:50:39 29 4
gpt4 key购买 nike

我创建了一个具有多个 View 的小应用程序。为此,我使用 Storyboard,并为每个 View 使用 View Controller 。现在,我必须存储用户可以在 View 上输入的数据。我想为此使用字典。我现在,如何创建字典:

NSMutableDictionary *globalData = [[NSMutableDictionary alloc] init];
//add keyed data
[globalData setObject:@"Object One" forKey:@"1"];
[globalData setObject:@"Object Two" forKey:@"2"];

我现在正在搜索添加和实例化该字典的正确位置,它可以在所有 View 中用作模型。

最佳答案

您可以使用单例模型对象来保存全局数据。如果您在几乎所有 viewController 中使用它,请在 *.pch 文件中声明。如果您使用字典,您可以定义一些常量以方便使用。

GlobalDataModel *model = [GlobalDataModel sharedDataModel];
//Pust some value
model.infoDictionary[@"StoredValue"] = @"SomeValue";
//read from some where else
NSString *value = model.infoDictionary[@"StoredValue"];

.h 文件

@interface GlobalDataModel : NSObject

@property (nonatomic, strong) NSMutableDictionary *infoDictionary;

+ (id)sharedDataModel;

@end

.m文件

@implementation GlobalDataModel

static GlobalDataModel *sharedInstance = nil;

- (id)init{
self = [super init];
if (self) {
self.infoDictionary = [NSMutableDictionary dictionary];
}

return self;
}

+ (id )sharedDataModel {
if (nil != sharedInstance) {
return sharedInstance;
}
static dispatch_once_t pred; // Lock
dispatch_once(&pred, ^{ // This code is called at most once per app
sharedInstance = [[self alloc] init];
});

return sharedInstance;
}

关于ios - 使用字典作为模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17122887/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com