get the array index in for statement in objective-c

后端 未结 5 1316
生来不讨喜
生来不讨喜 2021-01-14 21:33

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->$

相关标签:
5条回答
  • 2021-01-14 21:45

    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);
    }
    
    0 讨论(0)
  • 2021-01-14 21:57

    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++
    }
    
    0 讨论(0)
  • 2021-01-14 21:59

    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];
    }
    
    0 讨论(0)
  • 2021-01-14 21:59
    for (i=0;i<array.count;i++)
    {
      NSLog(@"Index=%d , Value=%@",i,[array objectAtIndex:i]);
    }
    

    Use this its simpler...

    hAPPY cODING...

    0 讨论(0)
  • 2021-01-14 22:07
    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]);
    }
    
    0 讨论(0)
提交回复
热议问题