2013-01-20 103 views
1

NSMutableArray,像這樣的對象:「0,1,0,1,1,1,0,0」獲取同一對象的索引中的NSMutableArray

,我需要得到所有對象的索引與值「1」

我試着用下面的代碼獲得它:

for (NSString *substr in activeItems){ 
      if ([substr isEqualToString:@"1"]){ 
       NSLog(@"%u",[activeItems indexOfObject:substr]); 
      } 
    } 

但因爲它在文檔方法indexOfObject:「回報說 - 最低的指數,其對應的陣列值等於anObject。 「

問題:我如何獲得值爲「1」的數組的所有索引?

回答

5

您可以使用NSArray這種方法:

- (NSIndexSet *)indexesOfObjectsPassingTest:(BOOL (^)(id obj, NSUInteger idx, BOOL *stop))predicate 

documentation here.

NSIndexSet *set = [array indexesOfObjectsPassingTest:^(id obj, NSUInteger idx, BOOL *stop) { 
    return [obj isEqualToString:@"1"]; 
}]; 

這就是你如何能得到的指標作爲一個數組中的元素(表示爲NSNumber objects):

NSIndexSet *set = // obtain the index set as above 

NSUInteger size = set.count; 

NSUInteger *buf = malloc(sizeof(*buf) * size); 
[set getIndexes:buf maxCount:size inIndexRange:NULL]; 

NSMutableArray *array = [NSMutableArray array]; 

NSUInteger i; 
for (i = 0; i < size; i++) { 
    [array addObject:[NSNumber numberWithUnsignedInteger:buf[i]]]; 
} 

free(buf); 

然後array將包含包裝在NSNumber中的匹配對象的所有索引。

+0

謝謝,但我怎麼能把所有數據從NSIndexSet NSMutableArray? – ignotusverum

+3

@anonymous例如,您可以遞歸地走它並使NSNumbers不在索引中。請花點時間研究文檔。 – 2013-01-20 12:22:55

3

只需使用索引ObjectObjectsPassingTest: NSArray的方法,提供一個塊作爲參數來檢查您的對象。

它將返回一個NSIndexSet。

- (NSIndexSet *)indexesOfObjectsPassingTest:(BOOL (^)(id obj, NSUInteger idx, BOOL *stop))predicate 

然後訪問索引從NSIndexSet

[indexset enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) { 
     //idx is what you want! 
}]; 
3

您可以使用[NSArray indexesOfObjectsPassingTest:]reference):

NSIndexSet *indexes = [activeItems indexesOfObjectsPassingTest:^BOOL (id obj, NSUInteger idx, BOOL *stop) { 
    return [obj isEqualToString:@"1"]; 
}]; 

一旦你的索引,你可以得到的子集原始數組,僅包含您感興趣的對象,使用[NSArray objectsAtIndexes:]reference):

NSArray *subset = [activeItems objectsAtIndexes:indexes]; 
+2

爲什麼說for循環調用'isEqualToString:'? – 2013-01-20 12:02:16

+0

@ H2CO3 true;修復。 – trojanfoe

+0

謝謝。現在很好。 – 2013-01-20 12:03:25

相關問題