Reputation: 49
in my program i want to add 20 objects to dictionary using for loop so i did
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);
but when i log it out of the loop i am getting only the last added values..not all the values..
Upvotes: 0
Views: 11690
Reputation: 1106
Use an array to store the records...
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
}
Upvotes: 2
Reputation: 10303
If you add 2 values with the same key only the last one will be shown as the other ones are all overwriten. You might want to (even tho it's not that pretty) add a dictionary for each loop to an array/dictionary.
Upvotes: 4