sys_debug
sys_debug

Reputation: 4003

getting the object value in key in dictionary

I have a dictionary with key-value pair populated from JSON returned data.What I wish to do is use the dictionary to populate UITableView.

I have this structure for table:

[Product Name] By [Manufacturer Name]

What this means is that key is Product Name and Value is Manufacturer Name. I need to get the name of the key and the name of the value. How can this be done? and is it possible without for-loop?

Upvotes: 2

Views: 5497

Answers (4)

s.bandara
s.bandara

Reputation: 5664

You can use the keyEnumerator of NSDictionary and for each key look up the value. This could look something like this:

for (NSString *p in dict)
{
    NSString *m = [dict objectForKey:p];
    // do something with (p,m)
}

You should not be concerned with avoiding for-loops. After all, something like a for loop will always happen somewhere underneath.

Upvotes: 4

Carl Veazey
Carl Veazey

Reputation: 18363

I'd use the enumerateKeysAndObjectsUsingBlock: method. The following code builds a list of the strings you require.

NSMutableArray *names = [NSMutableArray array];

[dictionary enumerateKeysAndObjectsUsingBlock: ^(NSString *key, NSString *object, BOOL *stop) {
    [names addObject[NSString stringWithFormat:@"%@ By %@",key, object]];
}];

Upvotes: 5

lakshmen
lakshmen

Reputation: 29064

NSArray * keys = [results allKeys];

for (int i = 0;i<[keys count];c++){
 NSString* productName = [key objectAtIndex:i];
 NSString* manufacturerName = [results objectForKey:productName];
}

Hope this helps...

I have assumed the name as strings, you can change the type according to your situation..

Upvotes: 1

user1983322
user1983322

Reputation:

If your keys are dynamic from json then you can use

 NSArray *keys = [dictionary allkeys];

Then in the table View Cell for row at index path method you can populate the table view with the corresponding keys and their values.

Upvotes: 1

Related Questions