【问题标题】:Pass NSIndexPath by reference通过引用传递 NSIndexPath
【发布时间】:2012-05-12 15:29:56
【问题描述】:

我正在使用 ARC,并希望创建一个通过引用传入 indexPath 的方法,以便我可以更改其值:

-(void)configureIndexPaths:(__bridge NSIndexPath**)indexPath anotherIndexPath:(__bridge NSIndexPath**)anotherIndexPath
{
      indexPath = [NSIndexPath indexPathForRow:*indexPath.row + 1 inSection:0];
      anotherIndexPath = [NSIndexPath indexPathForRow:*anotherIndexPath.row + 1 inSection:0];
}

但这给了我一个未找到属性行的错误。我该如何解决这个问题。

还有另一个概念性问题:如果我的目标只是更改传入方法的 indexPath 的值,难道不能通过指针传递吗?为什么我会选择引用传递而不是指针传递?

【问题讨论】:

  • 为什么不让方法返回一个新的 nsindexpath?
  • 我传入了两个我想要更改的唯一 indexPaths
  • newIndexPath 是单独的索引路径
  • 我一直认为双指针是 __autoreleasing,而不是 __bridge...

标签: objective-c ios automatic-ref-counting


【解决方案1】:

如果我的目标只是改变传递给方法的indexPath 的值,难道不能通过指针传递吗?

不是真的,因为索引路径是不可变的。您必须构造一个新的索引路径对象并返回它。

为什么我会选择通过引用而不是通过指针传递?

在 ObjC 中这样做的唯一真正原因是有多个返回值。这种技术最常见的用途是拥有一个返回对象或成功/失败指示符的方法,并且在必要时还可以设置错误对象。

在这种情况下,您有两个要从方法中取回的对象;一种方法是使用传递引用技巧。像现在一样传入两个索引路径可能会让你的生活更简单,但返回一个 NSArray 和新路径:

 - (NSArray *)configureIndexPaths:(NSIndexPath*)indexPath anotherIndexPath:( NSIndexPath*)anotherIndexPath
{
    NSIndexPath * newPath = [NSIndexPath indexPathForRow:[indexPath row]+1 inSection:0];
    NSIndexPath * anotherNewPath = [NSIndexPath indexPathForRow:[anotherIndexPath row]+1 inSection:0];
    return [NSArray arrayWithObjects:newPath, anotherNewPath, nil];
}

【讨论】:

  • 所以如果我通过指针传递并且我执行 indexPath = [NSIndexPath indexPathWith...],那么这不会改变使用该方法调用的原始索引路径的值吗?
  • 如果它看起来像(NSIndexPath **)arg{ *arg = [NSIndexPath indexPath...,从调用者的角度来看,这将改变传入的指针。
【解决方案2】:

你会这样做:

-(void) configureIndexPaths:(NSIndexPath*__autoreleasing *)indexPath anotherIndexPath:(__bridge NSIndexPath*__autoreleasing *)anotherIndexPath
{
    if (indexPath)
        *indexPath = [NSIndexPath indexPathForRow:[(*indexPath) row] + 1 inSection:0];
    if (anotherIndexPath)
        *anotherIndexPath = [NSIndexPath indexPathForRow:[(*indexPath) row] + 1 inSection:0];
}

您应该使用__autoreleasing,以便在创建对象时正确地自动释放对象,并检查传入的NULL 指针。如果您想要一个真正的pass-by-reference,请查看objc++ 和a NSIndexPath *&

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-12
    • 2013-09-10
    • 2020-04-01
    • 1970-01-01
    • 2011-06-28
    • 2015-07-22
    • 2015-05-02
    • 2012-03-13
    相关资源
    最近更新 更多