gpt4 book ai didi

ios - 由于未捕获的异常 'NSInvalidArgumentException' 访问 Web API 而终止应用程序

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:45:18 26 4
gpt4 key购买 nike

我正在尝试使用一个简单的 Web API,它使用 AFJSONRequestOperation 在 Objective C 中返回以下数据。

Results; (
{
Category = Groceries;
Id = 1;
Name = "Tomato Soup";
Price = 1;
},
{
Category = Toys;
Id = 2;
Name = "Yo-yo";
Price = "3.75";
},
{
Category = Hardware;
Id = 3;
Name = Hammer;
Price = "16.99";
}
)

我的 Objective-C 调用如下所示:

//not the real URL, just put in to show the variable being set
NSURL *url = [NSURL URLWithString:@"http://someapi"];

NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation;
operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request

success: ^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(@"Results; %@", JSON);
self.resultsArray= [JSON objectForKey:@"Results"];
}

failure: ^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error ,id JSON) {
//http status code
NSLog(@"Received Error: %d", response.statusCode);
NSLog(@"Error is: %@", error);
}
];

//run service
[operation start];

当我运行我的代码时,我可以看到 NSLog 语句中返回的数据。但是,当我尝试使用 JSON objectForKey 语句将结果设置到我的数组时,出现以下错误。

-[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0xe466510
2013-09-30 20:49:03.893 ITPMessageViewer[97459:a0b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0xe466510'

我是 Objective-C 的新手,无法弄清楚为什么它不起作用。任何帮助或想法将不胜感激。

最佳答案

你得到的结果是一个数组

objectForKey: 是一个 NSDictionary 方法

所以使用 valueForKey: 这是一个 NSArray 方法。

self.resultsArray= [JSON valueForKey:@"Results"];

关于ios - 由于未捕获的异常 'NSInvalidArgumentException' 访问 Web API 而终止应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19106789/

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