subodhbahl
subodhbahl

Reputation: 415

How to get the index of an object(occuring multiple times) in a NSMutableArray?

Hello folks :)

I have a quick question
- For the following NSMutableArray:

NSMutableArray *array = [[NSMutableArray alloc] initWithObjects: @"1", @"2",@"1",@"2",@"1"];

How can we get all the indexes for an object; supposedly I want to grab the index of 1?
So it should say 1 exists at index 0, 2 and 4.

Any kind of help is really appreciated :)
Thank you.

Upvotes: 0

Views: 403

Answers (2)

Andrew
Andrew

Reputation: 7720

- (NSIndexSet *)indexesMatchingObject:(id)anObject inArray:(NSArray *)anArray
{
    NSIndexSet *indexSet = [anArray indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
        return [obj isEqual:anObject];
    }];

    return indexSet;
}

use it like

NSMutableArray *array = [[NSMutableArray alloc] initWithObjects: @"1", @"2",@"1",@"2",@"1",nil];
NSIndexSet *matchesIndexSet = [self indexesMatchingObject:@"1" inArray:array];
NSLog(@"%@",matchesIndexSet);

returns

[number of indexes: 3 (in 3 ranges), indexes: (0 2 4)]

Upvotes: 3

Oliver
Oliver

Reputation: 23510

Did you try this :

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

That would give :

NSMutableArray *array = [[NSMutableArray alloc] initWithObjects: @"1", @"2",@"1",@"2",@"1", nil];

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

Best of all, you could create a NSArray category like this one :

.m file

@implementation NSArray(Upgraded)

- (NSIndexSet*) indexesMatchingObject:(id)objectToSearch
{
    NSIndexSet *index = [self indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
        return [obj isEqual:objectToSearch]);
    }];

    return index;
}

@end

That could be used like this :

NSMutableArray *array = [[NSMutableArray alloc] initWithObjects: @"1", @"2",@"1",@"2",@"1", nil];
NSIndexSet* index = [array indexesMatchingObject:@"1"];

Upvotes: 1

Related Questions