首頁  >  問答  >  主體

objective-c - iOS中遍歷NSDictionary有null和重複是什麼原因?

我在解析JSON的時候,到最後一步將字典內容遍歷到model的時候就會出現null和重複數據,之前的每一步都是正確的,用朋友自用伺服器的api測試有這個問題,我還用了百度APIStore裡的新聞API,也是同樣的問題,請問我是哪裡做錯了,請各位賜教,謝謝!

下面是程式碼,用的AFNetworking,JSON裡有5個數組,最底下是控制台截圖,用for循環和被註解掉的for in,都是一樣的問題

    [manager POST:@"地址不便透露,抱歉" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"成功");
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSArray *jData = [responseObject objectForKey:@"array"];
            //NSLog(@"%@",jData);
            
            for (NSDictionary * dict in jData)
            {
                NSArray * keys=[dict allKeys];
                JKey * jKey=[[JKey alloc]init];
                /*
                for (NSString * str in keys) {
                    //对对象的属性一一赋值 KVC
                    [jKey setValue:[dict objectForKey:str] forKey:str];
                    if ([dict objectForKey:str] > 0) {
                        [self.testArray addObject:jKey];
                    }
                }
                 */
                for (NSInteger i=0; i<keys.count; i++) {
                    [jKey setValue:[dict objectForKey:keys[i]] forKey:keys[i]];
                    NSLog(@"jKey=%@",jKey.coverpath);
                }
            }
        }

phpcn_u1582phpcn_u15822751 天前718

全部回覆(2)我來回復

  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-05-02 09:36:28

    自己試了一下,一一賦值就沒問題了

    for (NSDictionary * dict in jData)
    {
        JKey * jKey=[[JKey alloc]init];
        jKey.title = [dict valueForKey:@"title"];
        jKey.link = [dict valueForKey:@"link"];
        jKey.Id = [dict valueForKey:@"id"];
        jKey.coverpath = [dict valueForKey:@"coverpath"];
        [self.testArray addObject:jKey];
    }

    回覆
    0
  • 黄舟

    黄舟2017-05-02 09:36:28

    用MJExtension試試看
    for (NSInteger i = 0; i

    
         NormalModel * model = [NormalModel  objectWithKeyValues:array1[i]];
        
        [self.dataArray addObject:model];
    }

    回覆
    0
  • 取消回覆