- [__ NSCFArray objectForKeyedSubscript:]错误?

时间:2014-05-27 15:16:27

标签: ios

我登录后尝试从我的iOS应用程序中的JSON响应对象获取数据。但我仍然收到此错误。

错误:

'NSInvalidArgumentException', reason: '-[__NSCFArray objectForKeyedSubscript:]: unrecognized selector sent to instance 0x8fc29b0'

以下是我的请求代码,我正在使用AFNetworking:

self.operation = [manager GET:urlString parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSDictionary *JSON = (NSDictionary *)responseObject;
            NSDictionary *user = JSON[@"user"];
            NSString *token = user[@"auth_token"];
            NSString *userID = user[@"id"];
//            NSString *avatarURL = user[@"avatar_url"];
//            weakSelf.credentialStore.avatarURL = avatarURL;
            weakSelf.credentialStore.authToken = token;
            weakSelf.credentialStore.userId = userID;
            weakSelf.credentialStore.username = self.usernameField.text;
            weakSelf.credentialStore.password = self.passwordField.text;
            [SVProgressHUD dismiss];
            [self dismissViewControllerAnimated:YES completion:nil];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            if (operation.isCancelled) {
                return;
            }
            [SVProgressHUD showErrorWithStatus:@"Login Failed"];
            NSLog(@"%@", error);
        }]; 

JSON响应对象的外观如下:

<__NSCFArray 0x8cac0b0>(
{
    user =     {
        "auth_token" = b3a18e0fb278739649a23f0ae325fee1e29fe5d6;
        email = "jack@jack.com";
        id = 1;
        username = jack;
    };
}
)

我使用如下指针将数组转换为字典:

编辑:正如评论中指出的那样,任何其他人都会因为iOS知识有限而偶然发现。我在这里铸造而不是转换。有关完整说明,请参阅答案。

NSDictionary *JSON = (NSDictionary *)responseObject;

我是iOS的新手,如果问题很明显,请道歉。

感谢您的帮助。

3 个答案:

答案 0 :(得分:6)

你说:

  

我使用如下指针将数组转换为字典:

但这不是你在做什么。你正在投射它,但底层对象仍然是一个数组。


从JSON响应中,您可以看到那些JSON构造为具有单个元素(即字典)的数组。您可以致电[responseObject firstObject];来访问字典。当然,为了不让错误向另一个方向发展,你应该在响应对象上调用任何数组或字典特定方法之前检查输入的构造方式。

答案 1 :(得分:6)

你做的“转换”没有做任何转换,它是一个演员。这只是告诉编译器忽略它对这个对象知道的类型,并且好像它是你传递它的类型。

查看您的输出,您不会返回字典,而是使用单个字典的字典数组。要访问第一个字典,您可以使用它而不是强制转换:

NSDictionary *JSON = [responseObject objectAtIndex:0];

请注意,由于您从Web服务获取数据,因此您可能还应检查所获得的内容是否符合预期。

答案 2 :(得分:1)

你必须转换自己,但不要使用施法。

或者,这是检测json对象是否是数组或字典的代码

NSError *jsonError = nil;
id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&jsonError];

if ([jsonObject isKindOfClass:[NSArray class]]) {
    NSLog(@"its an array!");
    NSArray *jsonArray = (NSArray *)jsonObject;
    NSLog(@"jsonArray - %@",jsonArray);
}
else {
    NSLog(@"its probably a dictionary");
    NSDictionary *jsonDictionary = (NSDictionary *)jsonObject;
    NSLog(@"jsonDictionary - %@",jsonDictionary);
}