Reputation: 886
I have a Realm
model that contains a list of products:
class StorageArea: Object {
dynamic var name = ""
let products = List<Product>()
}
How can I sort the products alphabetically and persist the result in Realm? I cannot find any mutable method on the List class to reorder the elements and persist the ordered result.
I have a TableViewController
showing all the products. The user can move products in the tableView
, quit the app and restart the app: the ordered list of products is persisted. I am using List.move(from, to) for that.
Now I would like to add an option to sort the products alphabetically or by date. What would you recommend to modify the products list and save it?
Upvotes: 2
Views: 2733
Reputation: 7806
You can achieve that by retrieving first a sorted list of products, then remove all items from the list and re-add them all in the new order.
realm.write {
let storageArea = …
let sortedProducts = Array(storageArea.products.sorted("name"))
storageArea.products.removeAll()
storageArea.products.appendContentsOf(sortedProducts)
}
Upvotes: 6