ios - 在 objective-c 中,比较两个值时在 if 状态下不返回任何内容的目的是什么?

标签 ios objective-c cocoa-touch conditional-statements uitableview

下面的代码与 UIViewTable 一起使用,以帮助将行移动到表格中的不同位置。

无论如何,存在一个 if 语句,我正试图弄清楚它的用途。它不像 if 语句中有任何代码,所以它有什么用.. 如果 from 不等于 to 是否只是抛出错误?

我不明白它的用途,书上也没有解释。我猜 return; 什么都不返回。那么基本上是无效的?如果 to 等于 from,则什么都不会发生。

代码:

- (void)moveItemAtIndex:(int)from toIndex:(int)to
{
    if (from == to) {
        return;
    }

    // Get pointer to object being moved so we can re-insert it
    BNRItem *p = [allItems objectAtIndex:from];

    // Remove pointer from array
    [allItems removeObjectAtIndex:from];

    // Insert p in array at new location
    [allItems insertObject:p atIndex:to];
}

移动一行

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
    [[BNRItemStore sharedStore] moveItemAtIndex:[sourceIndexPath row] toIndex:[destinationIndexPath row]];
}

感谢您的宝贵时间 亲切的问候

最佳答案

return 通常用于从函数或方法返回一个值(因此得名)。在返回 void(无)的方法中,它可用于在该点退出该方法。

在您的示例中,如果 from 等于 to 则没有理由执行任何操作,因为您希望将一行移动到它已经位于的同一索引处.因此,您只需检查这种情况并从一开始就返回(并且不要执行以下三行)。

下面的代码会得到完全相同的结果,但是你有一个额外的缩进层,可以说它不是很优雅。

- (void)moveItemAtIndex:(int)from toIndex:(int)to
{
    if (from == to) {
        // do nothing
    } else {

        // Get pointer to object being moved so we can re-insert it
        BNRItem *p = [allItems objectAtIndex:from];

        // Remove pointer from array
        [allItems removeObjectAtIndex:from];

        // Insert p in array at new location
        [allItems insertObject:p atIndex:to];
    }
}

或者只是反转 if 语句,只在 from != to 时执行代码:

- (void)moveItemAtIndex:(int)from toIndex:(int)to
{
    if (from != to) {

        // Get pointer to object being moved so we can re-insert it
        BNRItem *p = [allItems objectAtIndex:from];

        // Remove pointer from array
        [allItems removeObjectAtIndex:from];

        // Insert p in array at new location
        [allItems insertObject:p atIndex:to];
    }
}

关于ios - 在 objective-c 中,比较两个值时在 if 状态下不返回任何内容的目的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20872240/

相关文章:

ios - apple pay 在真机上不可用

ios - didReceiveRemoteNotification : fetchCompletionHandler: download freezes

ios - UICollectionView 第一个单元格未正确对齐

objective-c - 如何创建 json 并将其发布到 Web 服务 Objective c

ios - 如何以编程方式在 Apple Watch UI 中创建带有分隔符的标签

objective-c - 2 单个 View 上的 TableView

ios - 如何向 Flutter 插件 iOS 项目添加新的 header ?

ios - 如何在 swift 中为 UILabel 加下划线?

ios - AVPlayer 在加密的 HLS 素材上崩溃

iphone - 如何改变HUD灰色部分的颜色