【问题标题】:Convert NSInteger to NSIndexpath将 NSInteger 转换为 NSIndexpath
【发布时间】:2026-01-21 04:55:02
【问题描述】:

基本上,我将数组的索引存储在 NSInteger 中。我现在需要它作为 NSIndexpath,我正在努力寻找并找到一种将我的 NSInteger 转换为 NSIndexpath 的方法,以便我可以重用它。

【问题讨论】:

  • 您需要NSIndexPath 做什么?你需要UITableView吗?
  • 在调用sqlite的更新语句时使用。我想我现在转换为 NSIndexPath 但我需要 NSIndexPath.row 这会引发错误。有什么想法吗?
  • 您可以在使用indexPathWithIndex: 创建的索引路径上调用row。创建索引路径可以调用row,可以使用indexPathForRow:inSection:

标签: ios objective-c nsindexpath nsinteger


【解决方案1】:

对于一个整数index

NSIndexPath *path = [NSIndexPath indexPathWithIndex:index];

根据the reference创建节点0中项目的索引以指向。

要在UITableView 中使用indexPath,更合适的方法是

NSIndexPath *path = [NSIndexPath indexPathForRow:row inSection:section];

【讨论】:

  • 谢谢。我还能做 path.row 还是让我的绒毛越过?
【解决方案2】:

如果您需要NSIndexPath 来替换UITableView,您可以使用indexPathForRow:inSection: (reference)。传递给表视图的索引路径必须恰好包含两个指定节和行的索引。使用indexPathWithIndex: 创建的索引路径仅包含一个索引,不适用于表格视图。

【讨论】:

    【解决方案3】:

    使用NSIndexPath类的以下方法。

    + (id)indexPathWithIndex:(NSUInteger)index;
    + (id)indexPathWithIndexes:(NSUInteger *)indexes length:(NSUInteger)length;
    - (id)initWithIndex:(NSUInteger)index
    

    如下使用,使用后别忘了releasemyIndexPath对象。

    NSIndexPath *myIndexPath = [[NSIndexPath alloc] initWithIndex:[myIntObj intValue]];
    

    【讨论】:

      【解决方案4】:

      斯威夫特 3:

      let indexPath = IndexPath(row: 0, section: 0)
      

      【讨论】: