如何从NSIndexset中获取索引到可可中的NSArray?

时间:2010-09-22 20:07:03

标签: objective-c cocoa nsindexset

我从表格视图中获取选择项目:

NSIndexSet *selectedItems = [aTableView selectedRowIndexes];

在NSArray对象中获取索引的最佳方法是什么?

5 个答案:

答案 0 :(得分:24)

枚举set,将NSNumbers从索引中删除,将NSNumbers添加到数组中。

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

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

答案 1 :(得分:12)

NSIndexSet *selectedItems = [aTableView selectedRowIndexes];

NSMutableArray *selectedItemsArray=[NSMutableArray array];
    [selectedItems enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) {
        [selectedItemsArray addObject:[NSNumber numberWithInteger:idx]];
    }];

答案 2 :(得分:3)

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

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

然后你可以做

selectedItems.toArray()

答案 3 :(得分: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

答案 4 :(得分:0)

以下是示例代码:

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

NSArray *theObjects = [theItems objectsAtIndexes:filteredObjects]

状况 适用于iOS 2.0及更高版本。