【发布时间】:2014-04-04 17:42:07
【问题描述】:
iOS SDK 中真的没有 API 可以使用 NSIndexPath 遍历/访问嵌套数组结构吗?我查看了NSIndexPath 和NSArray 的文档?
例如:
NSArray *nested = @[
@[
@[@1, @2], @[@10, @20]
],
@[
@[@11, @22], @[@110, @220]
],
@[
@[@111, @222], @[@1110, @2220]
]
];
如果我想对@222 的访问路径建模,我可以组装:
NSIndexPath *path = [[[NSIndexPatch indexPathWithIndex: 2] indexPathByAddingIndex: 0] indexPathByAddingIndex: 1];
所以我必须编写自己的递归访问器吗?
id probe = nested;
for (NSInteger position = 0; position < path.length; position++) {
probe = probe[path indexAtPosition: position];
}
令我惊讶的是,Apple 走了这么远来实际对构造进行建模,但却没有提供 API 将两者连接在一起。我希望在 NSArray 或 NSIndexPath 上使用一种方法,它允许执行以下操作:
id value = [nested objectAtIndexPath: path];
或者也许我错过了一个更惯用的转折?
更新:
我选择听从@CrimsonChris 的建议并整理了以下内容:
NSArray+NestedAccess.h
#import <Foundation/Foundation.h>
@interface NSObject (NestedAccess)
- (id) objectAtPath: (NSIndexPath*) path;
@end
NSArray+NestedAccess.c
#import "NSArray+NestedAccess.h"
@implementation NSArray (NestedAccess)
- (id) objectAtPath: (NSIndexPath*) path {
id probe = self;
for (NSInteger position = 0; position < path.length; position++) {
probe = ((NSArray*)probe)[path indexAtPosition: position];
}
return probe;
}
@end
【问题讨论】:
-
我真的不确定你在问什么。寻找
getIndexes:?indexPathWithIndexes:length:?indexAtPosition? -
如果你不害怕 swizelling,你可以做得更多:kickingbear.com/blog/archives/9
标签: ios objective-c ios7 nsarray nsindexpath