objective-c - 使用 NSIndexPath 将 2D NSArray 映射到 1D

标签 objective-c arrays multidimensional-array

我正在尝试以这种方式使用像二维数组一样的一维数组,但我无法弄清楚。 给定一个这样的数组:

NSArray *myArray = @[@0,@1,@2,@3,@4,@5];

是否可以使用这样定义的 NSIndexPath 访问“4”?:

NSIndexPath *index = [NSIndexPath indexPathForRow:1 inSection:1];

最佳答案

更一般地说,您可以使用维度 A 的索引路径来遍历维度 B 的数组。您还可以制定一个规则,说明当您的路径或数组中有额外维度时要做什么。

该规则可能看起来像这样:如果我用完了路径维度,则返回我在路径末尾找到的任何对象。如果我用完了数组维度(就像你问题中的情况)丢弃路径的剩余部分并返回我找到的任何非数组。

在代码中:

- (id)objectInArray:(id)array atIndexPath:(NSIndexPath *)path {

    // the end of recursion
    if (![array isKindOfClass:[NSArray self]] || !path.length) return array;

    NSUInteger nextIndex = [path indexAtPosition:0];

    // this will (purposely) raise an exception if the nextIndex is out of bounds
    id nextArray = [array objectAtIndex:nextIndex];

    NSUInteger indexes[27]; // maximum number of dimensions per string theory :)
    [path getIndexes:indexes];
    NSIndexPath *nextPath = [NSIndexPath indexPathWithIndexes:indexes+1 length:path.length-1];

    return [self objectInArray:nextArray atIndexPath:nextPath];
}

这样调用它......

NSArray *array = [NSArray arrayWithObjects:@1, [NSArray arrayWithObjects:@"hi", @"there", nil], @3, nil];

NSIndexPath *indexPath = [NSIndexPath indexPathWithIndex:1];
indexPath = [indexPath indexPathByAddingIndex:1];

NSLog(@"%@", [self objectInArray:array atIndexPath:indexPath]);

这会为给定的索引路径生成输出“there”。

关于objective-c - 使用 NSIndexPath 将 2D NSArray 映射到 1D,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13979938/

相关文章:

objective-c - 在 NSButton 子类中绘制文本

ios - 发射器不随父节点旋转

C - 在数组中使用 malloc() 存储指针,之后不能释放它们

java - 对行进行排序时,如何在多维数组中交换列?

php - 如何清空属于关联数组的键的内容而不取消 PHP 中的键设置?

java - 尝试使用二维数组和用户输入来设置大小来创建单词搜索?

iOS : Custom UISegmentedControl does not adjust when orientation is changed

ios - UISlider 平滑改变值

java - Java Card 中的内存分配

c++ - 将数组声明为静态不会使程序崩溃