gpt4 book ai didi

iphone - 使用allKeys时应用崩溃,是因为只有一个对象吗?

转载 作者:行者123 更新时间:2023-12-03 07:48:07 25 4
gpt4 key购买 nike

我不明白为什么 xcode 继续抛出这个错误

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-    
[__NSCFString allKeys]: unrecognized selector sent to instance 0x9367330'

每当我使用此代码时
NSDictionary *nextArray = [_classDictionary 
valueForKeyPath:@"response.page_records.page_record"];
for (NSDictionary *roster2 in nextArray) {
NSArray *keys = [roster2 allKeys];
if ([keys containsObject:@"title"]){
[pageName addObject:[roster2 objectForKey:@"title"]];
}
if ([keys containsObject:@"id"]) {
[pageID addObject:[roster2 objectForKey:@"id"]];
}
}

在尝试调试后,我发现只有当键只有一个对象时才会引发异常。例如,当“nextArray”是这样的:
 (
{
"class_id" = 0001;
"id" = 1234;
"title" = "First Page";
},
{
"class_id" = 0002;
"id" = 12345;
"title" = Assignments;
}
)

代码无异常运行,但是当代码很简单时
      {
"class_id" = 0001;
"id" = 1234;
"title" = "First Page";
}

抛出异常。为什么会发生这种情况?即使只有一个对象,键仍然包含对象标题。任何其他想法为什么会引发此异常?跟括号有关系吗? (总猜测)有没有更好的方法来调试真正发生的事情?

编辑:这是_userDictionary。拥有 objectforKey:@"title"的有序数组并避免上述错误的最佳方法是什么?
response =     {
"status" = ok;
"page_records" = {
"page" = 1;
"page_count" = 1;
"records_per_page" = 50;
"total_record_count" = 2;
"page_record" = (
{
"class_id" = 0001;
"id" = 1234;
"title" = "Test page";
},
{
"class_id" = 0002;
"id" = 12345;
"title" = "testing page 2";
}
);
};
};
}

最佳答案

在您的第一个示例中,您正在遍历字典数组,因此,NSArray *keys = [roster2 allKeys];正在调用一个数组。但是,在您的第二个示例中,您只有一本字典。它不是字典数组。所以你的循环for (NSDictionary *roster2 in nextArray)正在遍历字典的键,它们只是字符串,而不是数组。因此,错误。

首先,您的命名令人困惑。一个 NSDictionary命名为 nextArray ?试试这个:

id *response = [_classDictionary valueForKeyPath:@"response.page_records.page_record"];  
NSMutableArray *records;

if ([response isKindOfClass: [NSDictionary class]]) {
records = [[NSMutableArray alloc] init];
[records addObject: response];
}
else {
records = [NSMutableArray arrayWithArray: response];
}

for (NSDictionary *roster2 in records) {
NSArray *keys = [roster2 allKeys];
if ([keys containsObject:@"title"]){
[pageName addObject:[roster2 objectForKey:@"title"]];
}
if ([keys containsObject:@"id"]) {
[pageID addObject:[roster2 objectForKey:@"id"]];
}
}

关于iphone - 使用allKeys时应用崩溃,是因为只有一个对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8783720/

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