有没有办法在 0 索引处插入新项目到Realm容器?我在Realm类中没有看到插入方法。
我需要使用Lists 吗?如果答案是肯定的,我如何重构以下代码以能够使用Lists 并使 List 与Realm容器保持同步。换句话说,我很难想出一种在添加和删除时保持Realm容器和List相同项目的好方法。
在以下代码中,在最后一个索引处输入新项目。如何重组它以便能够在 0 索引处插入项目?
import RealmSwift
class Item:Object {
dynamic var productName = ""
}
Run Code Online (Sandbox Code Playgroud)
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)
}
}
}
Run Code Online (Sandbox Code Playgroud)
item = Item(value: ["productName": inputItem.text!])
try! realm.write {
realm.insert(item!, at:0)
}
Run Code Online (Sandbox Code Playgroud)
添加一个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)
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以将该ItemList.items对象直接用作表视图的数据源。
| 归档时间: |
|
| 查看次数: |
1879 次 |
| 最近记录: |