1

I've found a lot of documentation about how to code data into a key => value style, but how do i go about extracting the key & value from an array? I'm currently using NSArray.

What i'm after is the obj-c equivlant to php's foreach($array as $k => $v)

Simon.
  • 1,886
  • 5
  • 29
  • 62
  • possible duplicate of [for each loop in objective c for accessing NSMutable dictionary](http://stackoverflow.com/questions/2143372/for-each-loop-in-objective-c-for-accessing-nsmutable-dictionary) – Sebastian Jan 19 '15 at 13:26

3 Answers3

6

What are you looking for is NSDictionary. NSArray is accessible via indexes: 0, 1, 2 etc:

NSDictionary could be accessed like dict[@"key"] or [dict objectForKey:@"key"];

So, accessing NSArray would be:

for( int i = 0; i < [someArray count]-1; i++)
{
    NSLog(@"%@", someArray[i]);
}

while accessing your NSDictionary would be:

for (NSString* key in yourDict) {
    NSLog(@"%@", yourDict[key]);
    //or
    NSLog(@"%@", [yourDict objectForKey:key]);
}
Miknash
  • 7,888
  • 3
  • 34
  • 46
  • I'm time locked for another 10 minutes to accept this answer. I'll use `NSDictionary` `allKeys` to get the array of keys. thanks very much – Simon. Jan 19 '15 at 13:30
  • 2
    Also, be aware of difference between Mutable arrays and dictionaries and non mutable. Mutable can be changed but non mutable is set and unchangeable. Syntax for mutable is NSMutableArray and NSMutableDictionary, for non mutable NSArray and NSDictionary. – Miknash Jan 19 '15 at 13:52
0

An NSArray is like this :

NSArray *array = @[@"One", @"Two", @"Three"];

//Loop through all NSArray elements
for (NSString *theString in array) {
    NSLog(@"%@", theString);
}

//Get element at index 2
NSString *element = [array objectAtIndex:2];
//Or :
NSString *element = array[2];

If you have an object and you what to find its index in the array (object must be unique in array, otherwise will only return the first found) :

NSUInteger indexOfObject = [array indexOfObject:@"Three"];

NSLog(@"The index is = %lu", indexOfObject);

But if you are working with keys and values, maybe you need a NSDictionary.

An NSDictionary is like this :

NSDictionary *dictionary = @{@"myKey": @"Hello World !",
                             @"other key": @"What's up ?"
                             };

//Loop NSDictionary all NSArray elements
for (NSString *key in dictionary) {
    NSString *value = [dictionary valueForKey:key];
    NSLog(@"%@ : %@", key, value);
}
Niko
  • 3,412
  • 26
  • 35
-1

If u are having NSArray having number of dictionaries then u can get them as below

for(NSDictionary *dict in yourArray)
{
NSLog(@"The dict is:%@",dict);
NSLog(@"The key value for the dict is:%@",[dict objectForKey:@"Name"]);//key can be changed as per ur requirement
}

///(OR)

[yourdict enumerateKeysAndObjectsUsingBlock:^(id key, id object, BOOL *stop) {

NSLog(@"Key -> value of Dict is:%@ = %@", key, object);
}];

Hope it helps you...!

Vidhyanand
  • 5,369
  • 4
  • 26
  • 59