how can I get the array index within an “for (id item in items)” objective-c loop?

前端 未结 2 1821
不思量自难忘°
不思量自难忘° 2020-12-29 18:42

How can I get the array index within a \"for (id item in items)\" loop in objective-c? For NSArray or NSMutableArray for example.

For example:

for (         


        
相关标签:
2条回答
  • 2020-12-29 19:26

    Alternatively, you can use -enumerateObjectsUsingBlock:, which passes both the array element and the corresponding index as arguments to the block:

    [items enumerateObjectsUsingBlock:^(id item, NSUInteger idx, BOOL *stop)
    {
        …
    }];
    

    Bonus: concurrent execution of the block operation on the array elements:

    [items enumerateObjectsWithOptions:NSEnumerationConcurrent
        usingBlock:^(id item, NSUInteger idx, BOOL *stop)
    {
        …
    }];
    
    0 讨论(0)
  • 2020-12-29 19:35

    Only way I can think of is:

    NSUInteger count = 0;
    for (id item in items)
    {
        //do stuff using count as your index
        count++;
    }
    

    Bad Way

    Alternatively, you can use the indexOfObject: message of a NSArray to get the index:

    NSUInteger index;
    for (id item in items)
    {
        index = [items indexOfObject:item];
        //do stuff using index
    }
    
    0 讨论(0)
提交回复
热议问题