【问题标题】:How to create the "indexes" required for NSIndexPath:indexPathWithIndexes:length:如何创建 NSIndexPath:indexPathWithIndexes:length 所需的“索引”:
【发布时间】:2010-09-15 22:28:31
【问题描述】:

创建一个或多个节点的索引路径的类方法是:

+ (id)indexPathWithIndexes:(NSUInteger *)indexes length:(NSUInteger)length

我们如何创建第一个参数中所需的“索引”?

文档将其列为组成索引路径的索引数组,但它需要一个 (NSUinteger *)。

要创建1.2.3.4的索引路径,是不是简单的[1,2,3,4]数组?

【问题讨论】:

    标签: objective-c cocoa


    【解决方案1】:

    我用 2 行代码做到了这一点

     NSMutableArray *indexPaths = [[NSMutableArray alloc] init];   
     for (int i = firstIndexYouWant; i < totalIndexPathsYouWant; i++) [indexPaths addObject:[NSIndexPath indexPathForRow:i inSection:0]];
    

    简短、干净、易读。免费代码,别敲了。

    【讨论】:

    • 我会把第二行分成多行,伤我的眼睛
    【解决方案2】:

    在 iOS 上,你也可以从 NSIndexPath UIKit Additions 使用这个方法(在 UITableView.h 中声明):

    + (NSIndexPath*) indexPathForRow:(NSUInteger)row inSection:(NSUInteger)section
    

    【讨论】:

    • 啊哈!我在另一个 Q 中询问的“未记录的 API”的文档(各种)。谢谢! :)
    • 它有很好的记录:developer.apple.com/iphone/library/documentation/uikit/…,但是它只在 iphone (UIKit) 上可用。
    • 这个方法是在 NSIndexPath 中声明的,而不是在 UITableView 中声明的。
    • 上面的方法和下面的代码是一样的:NSUInteger indexes[] = {section, row}; [NSIndexPath indexPathWithIndexes:indexes length:2];(如果你同时针对iOS和Mac平台,NSIndexPath UIKit扩展是不可用的,所以你需要改用这种方法。 )
    【解决方案3】:

    你是对的。你可以这样使用它:

    NSUInteger indexArr[] = {1,2,3,4};
    
    NSIndexPath *indexPath = [NSIndexPath indexPathWithIndexes:indexArr length:4];
    

    【讨论】:

    • 对不起新手问题:使用后我需要[indexSet release]吗?
    • @Steve 在这种情况下不是。您将在 Cocoa 内存管理编程指南 (developer.apple.com/mac/library/documentation/cocoa/Conceptual/…) 中找到所有与 Cocoa 相关的内存管理问题的答案。因为indexPathWithIndexes:length 在选择器中没有“new”、“copy”或“alloc”,所以 Cocoa 规则指定它返回一个自动释放的实例。
    【解决方案4】:

    你的假设是正确的。它就像 NSUInteger 的 C 数组一样简单。 length 参数是索引数组中的元素个数。

    C 中的数组通常被标识为带有长度参数的指针(在本例中为 NSUInteger *)或已知的终止符,例如 C 字符串的 \0(它只是一个 char 数组)。

    【讨论】:

      猜你喜欢
      • 2021-10-25
      • 2018-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-23
      相关资源
      最近更新 更多