下面的代码与 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/