Multi NSDictionary返回字符串而不是子字符串

时间:2014-06-01 23:44:38

标签: ios objective-c json

我正在尝试从多个NSDictionary访问密钥。

这是我从NSLog输出的

Berlijn[23667:60b] data = {
    1 =     {
        data =         (
            4,
            0,
            0,
            0
        );
        key = "June 2014";
    };
}

当我尝试遍历此字典并记录密钥时,我得到NSInvalidArgumentException,因为key是一个NSString。

这是我目前的代码:

- (void) updateRating: (int) companyID {
    APICaller *api = [[APICaller alloc] init];

    [api setUrl:@"http://domain.examle/api/getcompanyhistory.php"];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *parameters = @{
                                 @"token": [[[FBSession activeSession] accessTokenData] accessToken],
                                 @"device_token" : [defaults stringForKey:@"uniqueToken"],
                                 @"companyid" : @(companyID)
                                 };



    [api setParameters: parameters];
    [api sendPostRequest: ^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"data = %@", responseObject);


        for(NSDictionary *contentData in responseObject) {

            NSLog(@"contentData = %@", [contentData objectForKey:@"key"]);
        }
        [self.tableView reloadData];

    }: ^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];
}

由于NSDictionary是一本字典,我不知道为什么它会返回一个字符串。

更新(错误消息):

2014-06-02 01:41:41.386 Berlijn[23747:60b] -[__NSCFString objectForKey:]: unrecognized selector sent to instance 0x1784253e0
2014-06-02 01:41:41.387 Berlijn[23747:60b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString objectForKey:]: unrecognized selector sent to instance 0x1784253e0'
*** First throw call stack:
(0x1860a309c 0x192021d78 0x1860a7d14 0x1860a5a7c 0x185fc54ac 0x1000eb8ac 0x1000ea014 0x1925f0420 0x1925f03e0 0x1925f356c 0x186062d64 0x1860610a4 0x185fa1b38 0x18b9c7830 0x188fe00e8 0x1000eaff4 0x19260baa0)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb) 

1 个答案:

答案 0 :(得分:3)

仅仅因为你打电话给contentData字典而不是一字典。

字典的快速枚举迭代键,而不是值。您的密钥是一个字符串(即使您将其称为NSDictionary),并且当您尝试在其上调用objectForKey:时会抛出异常。

由于responseObject是一个字典,您可以使用enumerateKeysAndObjectsUsingBlock:(void (^)(id key, id obj, BOOL *stop))迭代键和值。

另一种选择是正确使用快速枚举......

for(NSString *key in responseObject) {
    NSLog(@"contentData = %@", [responseObject objectForKey:key]);
}