0

在我的程序中,我想使用 for 循环将 20 个对象添加到字典中,所以我做到了

NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    self.responseData = nil;

    NSArray* latestLoans = [(NSDictionary*)[responseString JSONValue] objectForKey:@"loans"];
    NSLog(@"%i",[latestLoans count]);

parsedDict = [[NSMutableDictionary alloc] init];


for (int i=0; i<[latestLoans count]; i++) {


    //get latest loan
    NSDictionary* loan = [latestLoans objectAtIndex:i];

    //fetch the data
    NSNumber* fundedAmount = [loan objectForKey:@"funded_amount"];
    NSNumber* loanAmount = [loan objectForKey:@"loan_amount"];
    float outstandingAmount = [loanAmount floatValue] - [fundedAmount floatValue];

    NSString* name = [loan objectForKey:@"name"];
    NSString* country = [(NSDictionary*)[loan objectForKey:@"location"] objectForKey:@"country"];

    [parsedDict setObject:fundedAmount forKey:@"funded_amount"];
    [parsedDict setObject:loanAmount forKey:@"loan_amount"];
    [parsedDict setObject:name forKey:@"name"];
    [parsedDict setObject:country forKey:@"location"];
        }
nslog(@"%@",parsedDict);

但是当我将它从循环中注销时,我只得到最后添加的值..不是所有的值..

4

2 回答 2

4

如果您使用相同的键添加 2 个值,则只会显示最后一个值,因为其他值都将被覆盖。您可能想要(即使它不是那么漂亮)为每个循环添加一个字典到一个数组/字典。

于 2012-04-10T12:14:55.490 回答
2

使用数组来存储记录...

  NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
        self.responseData = nil;

        NSArray* latestLoans = [(NSDictionary*)[responseString JSONValue] objectForKey:@"loans"];
        NSLog(@"%i",[latestLoans count]);


     NSMutableArray someArray=[[NSMutableArray alloc]init];

    for (int i=0; i<[latestLoans count]; i++) {

    parsedDict = [[NSMutableDictionary alloc] init];
        //get latest loan
        NSDictionary* loan = [latestLoans objectAtIndex:i];

        //fetch the data
        NSNumber* fundedAmount = [loan objectForKey:@"funded_amount"];
        NSNumber* loanAmount = [loan objectForKey:@"loan_amount"];
        float outstandingAmount = [loanAmount floatValue] - [fundedAmount floatValue];

        NSString* name = [loan objectForKey:@"name"];
        NSString* country = [(NSDictionary*)[loan objectForKey:@"location"] objectForKey:@"country"];

        [parsedDict setObject:fundedAmount forKey:@"funded_amount"];
        [parsedDict setObject:loanAmount forKey:@"loan_amount"];
        [parsedDict setObject:name forKey:@"name"];
        [parsedDict setObject:country forKey:@"location"];
        [someArray addObject:parsedDict];
            }
    NSLog(@"%@",parsedDict);

//Read from Array


for(NSDictionary *tempDict in someArray) 
{
   //use [tempDict objectForKey:@"keyName"] to get values from each dictionary
} 
于 2012-04-10T12:19:13.197 回答