我有一个从另一个类更新的字典。我在字典上有一个属性观察者,所以我知道何时添加或删除了一个值。保持按索引更新字典值的有序数组
我创建了一个基于字典值的排序数组。我需要保持这个数组的更新,并保留与更新相关的索引,以便与UITableView一起使用。我的用户界面是这样的,批量重新加载数据是不可能的 - 我需要直接插入或删除基于更新的行。
我已经简化到这一个游乐场:
func dictionaryUpdated() {
print("dictionary updated")
// Add or remove string at index depending on order.
}
var myDictionary : [Int:String] = ["Bob".hashValue:"Bob","Dave".hashValue:"Dave","Yoda".hashValue:"Yoda","Windu".hashValue:"Windu","Obi Wan".hashValue:"Obi Wan","Qui-gon".hashValue:"Qui-gon","Anakin".hashValue:"Anakin"] { didSet { dictionaryUpdated() } }
func addEntry(entry: String) {
myDictionary[entry.hashValue] = entry
}
func removeEntry(entry: String) {
myDictionary.removeValueForKey(entry.hashValue)
}
// sort the keys alphabetically while creating the array
var valuesArray = myDictionary.values.sort { (lhs, rhs) -> Bool in
return lhs < rhs
}
我已经使用NSMutableOrderedSet尝试,但密钥只能是字符串。
有什么问题吗?您似乎找到了排序问题的解决方案,您是否遇到了该解决方案的一些问题? – Cristik
@Cristik是 - 我需要保持数组更新属性观察员触发字典值已更改,我需要保留排序的更新的索引与UITableView一起使用。 –
而且'valuesArray'没有办法吗?或者当字典内容改变时你有问题要检测吗? – Cristik