确定在排序后数组是否发生了变化。

3

我希望确定是否应该重新加载TableView。当它出现时,我会根据名称进行简单的排序。

我可以通过更多或更少的数据源项返回到此视图,或者数据源中的已更改项需要重新排序单元格。 例如,名称从Foo更改为Bar,因此顺序发生改变。

如何确定在使用Swift sort方法后列表是否发生了变化? 我正在寻找像这样的东西

let orderDidChange = clientList.sort({ $0.clientName < $1.clientName })

这是我的当前代码

override func viewWillAppear(animated: Bool) {

    super.viewWillAppear(animated)

    let originalList = clientList
    orderHasChanged = false

    clientList.sort({ $0.clientName < $1.clientName })
    clientList.sort({ $0.isBase > $1.isBase })

    orderHasChanged = clientList != originalList

    if orderHasChanged {
        // always enters here
        println("changed")
        tableView.beginUpdates()
        tableView.reloadSections(NSIndexSet(index: 0), withRowAnimation: UITableViewRowAnimation.Fade)
        tableView.endUpdates()
    }
    else {
        println("same do nothing")
    }

}

你能在排序后检查一下 originalList != clientList 吗? - Caleb
你可以这样做,但我不建议,甚至使用 let orderDidChange = clientList != clientList.sorted({ $0.clientName < $1.clientName }) - Caleb
我应该补充一下,dataSet 的一部分是使用 NSCoding 进行保存的,然后重新获取。因此,尽管是相同的对象,但内存地址现在位于不同的内存位置。所以 == 不起作用(除非我搞砸了)。也许我需要实现 equitable? - DogCoffee
是的,如果我手头的东西不起作用,那么这就超出了我的能力范围。我已经尝试过了,但很抱歉,我不能帮助你。 - Caleb
2个回答

2

您可以使用 == 运算符来检查旧数组是否等于排序后的数组。如果两个数组包含相同的数据但顺序不同,则它们不相等。

例如,

let bar: [String] = ["Hello", "World"]
let foo: [String] = ["Hello", "World"]

//this will print "true"
//bar and foo contain the same data in the same order
print(bar == foo)


let bar: [String] = ["Hello", "World"]
let foo: [String] = ["World", "Hello"]

//this will print "false"
//bar and foo contain the same data, but in a different order
print(bar == foo)

所以,类似这样的东西可以起作用。
let originalList = clientList
clientList.sort({ $0.clientName < $1.clientName })

let orderHasChanged = clientList != originalList

可以运行,只是在我的情况下不起作用。 - DogCoffee
@DogCoffee 尝试打印两个数组,看看你的结果是什么。 - Jojodmo
我进行了一项测试,与您展示的一样,比较功能按预期工作。但是只有在内存地址相同时才有效。因此,当我保存并重新初始化某些对象时,它们具有新的内存地址println(“address:\(unsafeAddressOf(clientList.first!))”),因此它们本质上是相同的 - 但这使比较无效。 - DogCoffee
@DogCoffee 我已经成功让它在playground中运行了(http://i.stack.imgur.com/3WHaK.png),并且两个数组具有不同的地址。 - Jojodmo

0

这是我能想到的最简短的方法。首先,您需要将标志添加为属性,然后使用修改后的排序方式,在其中基于是否已进行排序设置标志。如果已经排序,则重新加载您的tableView,否则不需要。

//private property
var hasBeenSorted = false

//var names = [3, 1, 4, 2]
var names = [1, 2, 3, 4]

names.sort({
    let isLess = $0 < $1

    //binary OR since we are interested only when it is true
    hasBeenSorted = isLess || hasBeenSorted 

    return isLess
})

hasBeenSorted //false

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接