Vlad Z.
Vlad Z.

Reputation: 3451

Get indexes of same object in NSMutableArray

I have NSMutableArray with objects like this : "0,1,0,1,1,1,0,0"

And i need to get indexes of all objects with value "1"

I'm trying to get it with following code:

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

But as it says in documentation method indexOfObject: " returns - The lowest index whose corresponding array value is equal to anObject."

Question: How i can get all indexes of array with value of "1" ?

Upvotes: 2

Views: 3290

Answers (3)

user529758
user529758

Reputation:

You can use this method of 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"];
}];

And this is how you can get the indexes as the elements of an array (represented by 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);

and then array will contain all the indexes of the matching objects wrapped in NSNumbers.

Upvotes: 5

Macmade
Macmade

Reputation: 54059

Simply use the indexesOfObjectsPassingTest: method of NSArray, providing a block as argument to check your objects.

It will return a NSIndexSet.

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

And then to access indexes from the NSIndexSet,

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

Upvotes: 4

trojanfoe
trojanfoe

Reputation: 122468

You can use [NSArray indexesOfObjectsPassingTest:] (reference):

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

Once you have the indexes, you can get the subset of the original array, containing just the objects you are interested in, using [NSArray objectsAtIndexes:] (reference):

NSArray *subset = [activeItems objectsAtIndexes:indexes];

Upvotes: 4

Related Questions