【发布时间】:2017-04-28 11:58:06
【问题描述】:
以下代码适用于添加新的ItemLists 和将新的Itemss 添加到ItemLists。我遇到的问题是从列表中删除所有项目。换句话说,我有一个按钮 (deleteAllItems),它应该从所选列表中删除所有项目,但我现在拥有它的方式会删除 Realm 中的 ALL Items无论是哪个列表拥有它们。
创建多个ItemLists 的正确方法是什么,它将包含多个Items 并能够从某个列表中删除所有Items?
ItemList 对象:
class ItemList: Object {
dynamic var listName = ""
dynamic var createdAt = NSDate()
let items = List<Item>()
}
项目对象:
class Item: Object {
dynamic var productName = ""
dynamic var createdAt = NSDate()
}
主控制器:
class ViewController: UIViewController, UITableViewDataSource{
@IBOutlet weak var tableListOfItems: UITableView!
@IBOutlet weak var inputProductName: UITextField!
@IBOutlet weak var inputListName: UITextField!
var allItems : Results<Item>!
override func viewDidLoad() {
super.viewDidLoad()
updateData()
}
@IBAction func addNewList(_ sender: Any) {
let list = ItemList()
list.listName = inputListName.text!
try! realm.write {
realm.add(list)
}
}
@IBAction func addNewItem(_ sender: Any) {
let newItem = Item()
newItem.productName = inputProductName.text!
let list = realm.objects(ItemList.self).filter("listName = 'List Name Here'").first!
try! realm.write {
list.items.append(newItem)
updateData()
}
}
func updateData(){
allItems = realm.objects(Item.self)
tableListOfItems.reloadData()
}
/// This deletes every Item in Realm which is not what
/// I want. I want to delete only items that belong to
/// a certain list. I tried...
/// let list = realm.objects(ItemList.self).filter("listName = 'Default List'").first!
/// list.items.removeAll()
@IBAction func deleteAllItems(_ sender: Any) {
try! realm.write {
realm.delete(realm.objects(Item.self))
updateData()
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return allItems.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath)
let data = allItems[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 = allItems?[indexPath.row] {
try! realm.write {
realm.delete(item)
}
tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
}
}
}
}
【问题讨论】:
标签: ios swift realm one-to-many