OGeek|极客世界-中国程序员成长平台

标题: objective-c - 通过引用传递 NSIndexPath [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 13:47
标题: objective-c - 通过引用传递 NSIndexPath

我正在使用 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 的值,难道不能通过指针传递吗?为什么我会选择引用传递而不是指针传递?



Best Answer-推荐答案


if my my goal is just to change the value of indexPath that was passed in to the method, couldn't passing by pointer also do that?

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

Why would I choose to pass by reference rather than pass by pointer?

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

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

 - (NSArray *)configureIndexPathsNSIndexPath*)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];
}

关于objective-c - 通过引用传递 NSIndexPath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10565031/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4