大佬教程收集整理的这篇文章主要介绍了ios – 如何将0索引处的项目插入Realm容器,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要使用列表吗?如果答案是肯定的,我如何重构以下代码以便能够使用列表并使List与Realm容器保持同步.换句话说,在添加和删除时,我很难想出一个很好的方法来保持Realm容器和List具有相同的项目.
在以下代码中,在最后一个索引处输入新项目.如何重组它以便能够在0索引处插入项目?
模型类
import RealmSwift class Item:Object { dynamic var productName = "" }
主ViewController
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) }
这种实现的最佳实践是创建另一个包含List属性的Object模型子类,在Realm中保留它的一个实例,然后将每个对象添加到该属性.列表属性的行为与普通数组类似,因此可以非常快速有效地按以下方式排列对象:
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对象作为表视图的数据源.
以上是大佬教程为你收集整理的ios – 如何将0索引处的项目插入Realm容器全部内容,希望文章能够帮你解决ios – 如何将0索引处的项目插入Realm容器所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。