通过索引和元素枚举 NSArray 的惯用方法



我需要做一些类似于python的enumerate()函数的事情,在iOS中有一个NSArray(我必须构建NSIndexPath对象并检查对象)。

我没有看到一个内置的方法可以做这样的事情(即没有NSArray等效于NSDictionary的枚举键和对象使用块:方法)。这给我留下了我能想到的两种一般方法。

for (NSUInteger index = 0; index < mySequence.count; index++) {
    MyElementType *element = mySequence[index];
    //
    // code that works with both index and element
    //
}

NSUInteger index = 0;
for (MyElementType *element in mySequence) {
    //
    // code that works with both index and element
    //
    index++;
}

有没有充分的理由更喜欢另一个?还是有第三种方法比其中任何一种方法更好?

NSArray 中存在以下 API:

- (void)enumerateObjectsUsingBlock:(void (^)(id obj, NSUInteger idx, BOOL *stop))

最新更新