2

I am stuck in a stupid mess...
I want to get not only the value of an array but also the index of the values.
In PHP it's simple: foreach($array as $key->$value) Here $key will contain the index value.
Isn't there a similar approach in objective c?
How else could I achieve this? Please help! :((

5 Answers 5

7

Arrays not like in php are numbered 0-size of array. I guess you talking about dictionary's. If so you can get array of key with [dict allKeys]. so something like this should work:

for(id key in [dict allKeys]){
  id value = [dict objectForKey:key];
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks :).. you're right...i was messed up with dictionary and arrays (because associative arrays in php are so much like dictionary in objective-c!). Now using dictionary, i can make use of key and its value!
3

If you're on iOS4 you can do

[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
                                   {
                                       NSLog(@"%@ is at index %u", obj, idx);
                                   }];

on iOS 3.x you can do

NSUInteger idx = 0;
for (id obj in array)
{
    NSLog(@"%@ is at index %u", obj, idx);
    idx++
}

2 Comments

Just curious, is -objectForKey: any better/worse than incrementing the variable idx?
objectForKey: would only work for dictionaries. The discussion here was about arrays.
1
for (i=0;i<array.count;i++)
{
  NSLog(@"Index=%d , Value=%@",i,[array objectAtIndex:i]);
}

Use this its simpler...

hAPPY cODING...

Comments

0

I'm unable to test it, but I think I did do something similar the other night. From this wiki it looks like you can do something like

for(id key in d) {
    NSObject *obj = [d objectForKey:key];      // We use the (unique) key to access the (possibly non-unique) object.
    NSLog(@"%@", obj);
}

1 Comment

I am not sure why this would be -1'ed, I wouldn't use NSObject *... but that is more of a stylistic thing...
0
int arraySize = array.count;
// No need to calculate count/size always
for (int i=0; i<arraySize; i++)
{
    NSLog(@"Index=%d , Value=%@",i,[array objectAtIndex:i]);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.