Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get indexes from NSIndexset into an NSArray in cocoa?

I'm getting the select items from a table view with:

NSIndexSet *selectedItems = [aTableView selectedRowIndexes];

what's the best way to get the indexes in a NSArray object?

like image 572
Mr_Nizzle Avatar asked Sep 22 '10 20:09

Mr_Nizzle


People also ask

Can Nsarray contain nil?

arrays can't contain nil.

Is Nsarray ordered?

An object representing a static ordered collection, for use instead of an Array constant in cases that require reference semantics.

What is NSIndexSet?

The NSIndexSet class represents an immutable collection of unique unsigned integers, known as indexes because of the way they are used. This collection is referred to as an index set. Indexes must be in the range 0 .. NSNotFound - 1 . You use index sets in your code to store indexes into some other data structure.


2 Answers

Enumerate the set, make NSNumbers out of the indexes, add the NSNumbers to an array.

That's how you'd do it. I'm not sure I see the point in transforming a set of indexes into a less efficient representation, though.

To enumerate a set, you have two options. If you're targeting OS X 10.6 or iOS 4, you can use enumerateIndexesUsingBlock:. If you're targeting earlier versions, you'll have to get the firstIndex and then keep asking for indexGreaterThanIndex: on the previous result until you get NSNotFound.

like image 105
Chuck Avatar answered Oct 01 '22 10:10

Chuck


NSIndexSet *selectedItems = [aTableView selectedRowIndexes];

NSMutableArray *selectedItemsArray=[NSMutableArray array];
    [selectedItems enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) {
        [selectedItemsArray addObject:[NSNumber numberWithInteger:idx]];
    }];
like image 14
Luc-Olivier Avatar answered Oct 01 '22 10:10

Luc-Olivier