gpt4 book ai didi

ios - 用于创建 NSDictionary 的 Objective-C foreach 不起作用

转载 作者:行者123 更新时间:2023-11-28 20:04:44 25 4
gpt4 key购买 nike

我正在尝试使用以下代码对 NSDictionary 进行排序:

NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableLeaves error:&err];
for (NSDictionary* lesson in jsonDict[@"data"][@"lessons"]) {
data[lesson[@"day"]][lesson[@"index"]][@"title"] = lesson[@"title"];
}

如果我记录 lesson[@"day"] 等的值,这些值似乎是正确的。不知何故,如果我在循环后记录 data[@"1"][@"1"] 它只是空的。所以问题似乎是将值设置到 NSDictionary 数据中。

原始 JSON 字符串包含一个包含所有类(class)的列表。为了正确访问它们,我想要一个这种格式的新 NSDictionary:data[day][index][field]

JSON 代码如下所示:

{"status":"success","data":{"lessons":[{"id":1,"index":"1","day":"1","title":"Mathe","teacher":"Mr. xyz","room":"103","ind":"1"},{"id":2,"index":"1","day":"2","title":"Physik","teacher":"Mr xyz","room":"PH4","ind":"1"},...

最佳答案

问题是(我假设)

data[lesson[@"day"]][lesson[@"index"]][@"title"] = lesson[@"title"];

不会自动创建中间字典

data[lesson[@"day"]]
data[lesson[@"day"]][lesson[@"index"]]

你必须首先检查它们是否存在,如果它们还不存在则分配一个可变字典存在。 (没有 Perl 哈希的 Autovivification!)像这样:

if (data[lesson[@"day"]] == nil) {
data[lesson[@"day"]] = [NSMutableDictionary dictionary];
}
if (data[lesson[@"day"]][lesson[@"index"]] == nil) {
data[lesson[@"day"]][lesson[@"index"]] = [NSMutableDictionary dictionary];
}
data[lesson[@"day"]][lesson[@"index"]][@"title"] = lesson[@"title"];

完整的工作代码:

NSString *str = @"{\"status\":\"success\",\"data\":{\"lessons\":[{\"id\":1,\"index\":\"1\",\"day\":\"1\",\"title\":\"Mathe\",\"teacher\":\"Mr. xyz\",\"room\":\"103\",\"ind\":\"1\"},{\"id\":2,\"index\":\"1\",\"day\":\"2\",\"title\":\"Physik\",\"teacher\":\"Mr xyz\",\"room\":\"PH4\",\"ind\":\"1\"}]}}";
NSError *err;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableLeaves error:&err];
NSMutableDictionary *data = [NSMutableDictionary dictionary];

for (NSDictionary* lesson in jsonDict[@"data"][@"lessons"]) {
if (data[lesson[@"day"]] == nil) {
data[lesson[@"day"]] = [NSMutableDictionary dictionary];
}
if (data[lesson[@"day"]][lesson[@"index"]] == nil) {
data[lesson[@"day"]][lesson[@"index"]] = [NSMutableDictionary dictionary];
}
data[lesson[@"day"]][lesson[@"index"]][@"title"] = lesson[@"title"];
}
NSLog(@"%@", data);

输出:

{    1 =     {        1 =         {            title = Mathe;        };    };    2 =     {        1 =         {            title = Physik;        };    };}

关于ios - 用于创建 NSDictionary 的 Objective-C foreach 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22455858/

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