Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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" ?

like image 971
ignotusverum Avatar asked Mar 10 '26 23:03

ignotusverum


2 Answers

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.

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];
like image 34
trojanfoe Avatar answered Mar 13 '26 13:03

trojanfoe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!