使用for循环将对象添加到字典中

时间:2012-04-10 12:10:04

标签: iphone ios for-loop nsdictionary nsmutabledictionary

在我的程序中我想使用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);

但是当我将它记录出循环时,我只得到最后添加的值..不是所有的值..

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分: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
}