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 に答える