17

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?

4

5 回答 5

24

枚举集合,从索引中生成 NSNumbers,将 NSNumbers 添加到数组中。

你就是这样做的。不过,我不确定我是否看到了将一组索引转换为效率较低的表示的意义。

要枚举一个集合,您有两个选择。如果您的目标是 OS X 10.6 或 iOS 4,您可以使用enumerateIndexesUsingBlock:. 如果您的目标是较早的版本,则必须先获取firstIndex,然后继续询问indexGreaterThanIndex:先前的结果,直到获取NSNotFound.

于 2010-09-22T20:10:57.930 回答
13
NSIndexSet *selectedItems = [aTableView selectedRowIndexes];

NSMutableArray *selectedItemsArray=[NSMutableArray array];
    [selectedItems enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) {
        [selectedItemsArray addObject:[NSNumber numberWithInteger:idx]];
    }];
于 2014-05-11T15:58:41.613 回答
3

使用 swift 您可以执行以下操作

extension NSIndexSet {
    func toArray() -> [Int] {
        var indexes:[Int] = [];
        self.enumerateIndexesUsingBlock { (index:Int, _) in
            indexes.append(index);
        }
        return indexes;
    }
}

那么你可以做

selectedItems.toArray()
于 2015-03-10T12:42:43.540 回答
1

我通过在 NSIndexSet 上创建一个类别来做到这一点。这使它保持小而高效,我只需要很少的代码。

我的界面(NSIndexSet_Arrays.h):

/**
 *  Provides a category of NSIndexSet that allows the conversion to and from an NSDictionary
 *  object.
 */
@interface NSIndexSet (Arrays)

/**
 *  Returns an NSArray containing the contents of the NSIndexSet in a format that can be persisted.
 */
- (NSArray*) arrayRepresentation;

/**
 *  Initialises self with the indexes found wtihin the specified array that has previously been
 *  created by the method @see arrayRepresentation.
 */
+ (NSIndexSet*) indexSetWithArrayRepresentation:(NSArray*)array;

@end

和实现(NSIndexSet_Arrays.m):

#import "NSIndexSet_Arrays.h"

@implementation NSIndexSet (Arrays)

/**
 *  Returns an NSArray containing the contents of the NSIndexSet in a format that can be persisted.
 */
- (NSArray*) arrayRepresentation {
    NSMutableArray *result = [NSMutableArray array];

    [self enumerateRangesUsingBlock:^(NSRange range, BOOL *stop) {
        [result addObject:NSStringFromRange(range)];
    }];

    return [NSArray arrayWithArray:result];
}

/**
 *  Initialises self with the indexes found wtihin the specified array that has previously been
 *  created by the method @see arrayRepresentation.
 */
+ (NSIndexSet*) indexSetWithArrayRepresentation:(NSArray*)array {
    NSMutableIndexSet *result = [NSMutableIndexSet indexSet];

    for (NSString *range in array) {
        [result addIndexesInRange:NSRangeFromString(range)];
    }

    return result;
}


@end
于 2015-06-24T04:10:49.027 回答
1

这是示例代码:

NSIndexSet *filteredObjects = [items indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {do testing here}];

NSArray *theObjects = [theItems objectsAtIndexes:filteredObjects]

可用性 适用于 iOS 2.0 及更高版本。

于 2015-09-01T09:30:27.527 回答