user831679
user831679

Reputation:

Getting Array from for loop iterations in Objective-C

I am using this code to get the values of JSON,

    NSDictionary *dict = [list objectAtIndex: 0];

vehicleList = [dict objectForKey: @"assets"];

NSString *identity = [dict objectForKey: @"identity"];

for (NSUInteger index = 0; index < [vehicleList count]; index++) {

    itemDict = [vehicleList objectAtIndex: index];

    NSMutableArray *listVehicles = [itemDict objectForKey: @"identity"];

    NSLog(@"Assets: %@", listVehicles);
}

it is working properly and showing exact results

Assets: 34DL3611
Assets: 34GF0512
Assets: 34HH1734
Assets: 34HH1736
Assets: 34YCJ15

I want to use these values to populate an array so that I would use that array for tableview.

Upvotes: 0

Views: 151

Answers (2)

Ryan Crews
Ryan Crews

Reputation: 3033

If I'm reading what you're saying correctly I would suggest creating your for loop slightly differently to increase readability and streamline the method.

NSDictionary * dict = [list objectAtIndex: 0];
NSArray * vehicles  = [dict objectForKey:@"assets"];


NSMutableArray * listVehicles = [NSMutableArray arrayWithCapacity:vehicles.count];


for (NSDictionary * currentDictionary in vehicles)
{
    NSString * identity = [currentDictionary objectForKey:@"identity"];

    [listVehicles addObject:identity];
    NSLog(@"Added %@ to the array, which is now contains %d objects", identity, listVehicles.count);
}

This is a nice built in feature that keeps you from needing to deal with counts and calling objectForIndexAt:

I just quickly typed that up, but I'm pretty sure it does what you're doing. If not though, I still encourage you to tweak it and use that iteration style, I think you'll like it.

Upvotes: 1

Bourne
Bourne

Reputation: 10312

Make your listVehicles a NSMutableArray and do [listVehicles addObject:[itemDict objectForKey:@"identity"]] instead of what you are currently doing inside your loop.

Upvotes: 3

Related Questions