iOS官方文档 Foundation篇---NSIndexPath

昂首千丘远,啸傲风间,堪寻敌手共论剑,高处不胜寒。

——风之痕

NSIndexPath

索引列表,它们一起表示嵌套数组树中特定位置的路径。

索引路径中的每个索引表示从树中的一个节点到另一个更深的节点的子数组的索引。
创建索引路径
//创建空索引
NSIndexPath *indexPath = [[NSIndexPath alloc]init];//输出:{length = 0, path = }
 
//创建单节点索引路径
NSIndexPath *indexPath1 = [NSIndexPath indexPathWithIndex:1];//输出:{length = 1, path = 1}
 
//创建具有一个或多个节点的索引路径。
NSUInteger indexs[] = {1,2,3,4,5};
NSIndexPath *indexPath2 = [NSIndexPath indexPathWithIndexes:indexs length:5];//输出:{length = 5, path = 1 - 2 - 3 - 4 - 5}
更改索引路径
//索引添加新节点,返回新的索引
NSIndexPath *indexPath3 = [indexPath1 indexPathByAddingIndex:2];//输出:{length = 2, path = 1 - 2}
 
//移除索引尾部节点,返回新的索引
NSIndexPath *indexPath4 = [indexPath2 indexPathByRemovingLastIndex];//输出:{length = 4, path = 1 - 2 - 3 - 4}

//将索引路径中存储的索引从位置范围指定的位置复制到指定的索引中
[indexPath2 getIndexes:indexs range:NSMakeRange(0, indexPath2.length-2)];//输出:{length = 5, path = 1 - 2 - 3 - 4 - 5}
访问索引路径值
//返回索引指定节点的值
NSUInteger index = [indexPath2 indexAtPosition:1];//输出:2
 
//返回索引路径中的节点数
NSUInteger count = indexPath2.length;//输出:5
比较索引
//比较索引
/*
  typedef NS_CLOSED_ENUM(NSInteger, NSComparisonResult) {
      NSOrderedAscending = -1L,升序
      NSOrderedSame,相等
      NSOrderedDescending 降序
  };
*/
NSComparisonResult result = [indexPath1 compare:indexPath2];//输出:NSOrderedAscending

NSIndexPath (UIKitAdditions)

UIKIt框架下的索引方法,针对于UITableView与UICollectionView
UITableView-索引路径创建与访问
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];//输出:{length = 2, path = 0 - 0}
NSInteger section = indexPath.section;//0
NSInteger row = indexPath.row;//0
UICollectionView-索引路径创建与访问
NSIndexPath *indexPath1 = [NSIndexPath indexPathForItem:0 inSection:0];//输出:{length = 2, path = 0 - 0}
NSInteger item = indexPath1.item;//0
欢迎留言指正,会持续更新。。。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容