Based on the following code I would like to be able to create a new ItemList
from an existing one. In other words I have an ItemList
called First List
and I want to create a new ItemList
, call it Second List
and fill it with the Item
s from First List
.
The way I have it right now is that it creates the Second List
as expected, the Item
s from the First List
show in Second List
but what doesn't work is when I want to delete only the Item
s from First List
, it deletes Item
s from both lists. I guess I'm not truly copying the items.
So the question is, how can I copy Item
s from First List
to Second List
?
Object Models:
class ItemList: Object {
dynamic var listName = ""
dynamic var createdAt = NSDate()
let items = List<Item>()
}
class Item:Object{
dynamic var productName:String = ""
dynamic var createdAt = NSDate()
}
Code to create Second List
from First List
This Works fine, it creates Second List
and adds the items from First List
but I don't think I'm making copies just showing them in Second List
.
let newList = ItemList()
newList.listName = "Second List"
if let selectedList = realm.objects(ItemList.self).filter("listName = %@", "First List").first{
let itemsFromFirstList = selectedList.items
newList.items.append(objectsIn:itemsFromFirstList)
}
try! realm.write {
realm.add(newList)
}
This code is supposed to delete only the items from First List
This actually deletes items from both First List
and Second List
let listToDelete = realm.objects(ItemList.self).filter("listName = %@", "First List").first
try! realm.write {
for item in (listToDelete?.items)! {
realm.delete(realm.objects(Item.self).filter("productName = %@", item.productName).first!)
}
}