2011-06-11 57 views
0

是否有一種簡單的方法可以快速枚舉數組中的一系列對象?喜歡的東西...Objective-C - 快速枚舉數組的子集?

for (Object *object in myArray startingAtIndex:50) { 
    //do stuff 
} 

...避免不得不做這樣的事情......

for (Object *object in myArray) { 
    NSUInteger index = [myArray indexOfObject:object]; 
    if (index >= 50) { 
     //do stuff 
    } 
} 

感謝。

回答

5

這些都在我的腦海:

for (Object *object in [myArray subArrayWithRange:NSMakeRange(50, ([myArray count] - 49))]) { 
    //do stuff 
} 

這比手動枚舉這樣雖然會創建一個臨時數組,從而潛在地更慢(基準它!):

NSUInteger arrayCount = [myArray count]; 
for (NSUInteger i = 50; i < arrayCount; i++) { 
    Object *object = [myArray objectAtIndex]; 
    // do stuff 
} 
+0

無論是更快不得不通過分析確定。 'subArrayWithRange:'方法可能會更快。 – Sven 2011-06-11 16:24:52

+0

是的,因此「潛在」。 ;) – Regexident 2011-06-11 16:26:33

+0

你的意思是'我 DenverCoder9 2011-06-11 16:47:28

6

如果myArray是不可改變,那麼subArrayWithRange:可能是不會複製指針,雖然retain可能仍然必須發送到everyt在子陣列中興奮。

總的來說,這並不重要。我老實說從未見過一個例子,即快速枚舉與indexOfObject:足以導致性能問題值得關注(總會有更糟的情況:)。

另一種方法;使用enumerateBlock:並簡單地從索引返回遊俠(並使用停止標誌)。

[myArray enumerateWithBlock: ^(id o, NSUInteger i, BOOL *f) { 
    if (i < 10) return; 
    if (i > 20) { *f = YES; return; } 
    ... process objects in range ... 
}]; 

(你甚至可以使用options:變種同時枚舉。)

+0

+1 - 雖然我沒有使用解決方案,但這也是很好的建議。 – DenverCoder9 2011-06-13 11:01:07