有没有办法在 0 索引处插入新项目Realm
容器?我在中没有看到插入方法Realm
class.
我需要使用吗List
是?如果答案是肯定的,我如何重构以下代码才能使用List
s 并保持列表与Realm
容器。换句话说,我很难想出一个好方法来保持Realm
容器和List
添加和删除时使用相同的项目。
在以下代码中,新项目将在最后一个索引处输入。如何重构它以便能够在 0 索引处插入项目?
模型类
import RealmSwift
class Item:Object {
dynamic var productName = ""
}
主视图控制器
let realm = try! Realm()
var items : Results<Item>?
var item:Item?
override func viewDidLoad() {
super.viewDidLoad()
self.items = realm.objects(Item.self)
}
func addNewItem(){
item = Item(value: ["productName": productNameField.text!])
try! realm.write {
realm.add(item!)
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.items!.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reusableCell", for: indexPath)
let data = self.items![indexPath.row]
cell.textLabel?.text = data.productName
return cell
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == UITableViewCellEditingStyle.delete{
if let item = items?[indexPath.row] {
try! realm.write {
realm.delete(item)
}
tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
}
}
}
理想情况下,这是我希望在 addNewItem() 方法中插入新项目时能够执行的操作...
item = Item(value: ["productName": inputItem.text!])
try! realm.write {
realm.insert(item!, at:0)
}
添加一个sortedIndex
允许您手动控制对象排序的整数属性绝对是 Realm 中比较流行的对象排序方式之一,但效率相当低。为了在 0 处插入一个对象,您需要循环遍历所有其他对象并将其排序号加 1,这意味着您最终需要接触数据库中该类型的每个对象才能执行此操作。
这种实现的最佳实践是创建另一个Object
模型子类包含List
属性,在 Realm 中保留它的一个实例,然后将每个对象添加到其中。List
属性的行为类似于普通数组,因此可以非常快速有效地以这种方式排列对象:
import RealmSwift
class ItemList: Object {
let items = List<Item>()
}
class Item: Object {
dynamic var productName = ""
}
let realm = try! Realm()
// Get the list object
let itemList = realm.objects(ItemList.self).first!
// Add a new item to it
let newItem = Item()
newItem.productName = "Item Name"
try! realm.write {
itemList.items.insert(newItem, at: 0)
}
然后您可以使用ItemList.items
对象直接作为表视图的数据源。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)