Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make RLMResults mutable?

Tags:

ios

iphone

realm

The Realm doc says the RLMResults are lick NSArray. I have some results returned from the database and I want to merge it into another RLMResults. But it seems it's immutable, How to make a RLMResults add objects from another RLMResults? or make it mutable? or convert it to NSArray?

like image 824
yong ho Avatar asked Sep 29 '22 14:09

yong ho


2 Answers

Currently this is something you would have to do manually. You could create an RLMArray by concatenating your two results.

We are discussing a union/merge method further down on the roadmap for RLMObjects of the same type though.

Any bit you can share will help us understand the use cases and potentially impact the api design

As long as they are the same type, here's a generic example

let currentTask = Task.objectsWhere("name = %@", "First task").firstObject() as Task
let currentRecords = currentTask.records
let arrayOfRecords = RLMArray(objectClassName: "Record")

arrayOfRecords.addObjects(currentRecords)

let futureTask = Task.objectsWhere("name = %@", "Future task").firstObject() as Task
let futureRecords = futureTask.records

arrayOfRecords.addObjects(futureRecords)
like image 194
yoshyosh Avatar answered Oct 06 '22 19:10

yoshyosh


I found out the solution from duemunk: https://github.com/realm/realm-cocoa/issues/1046

Basically I convert the RLMResults to [RLMObject]: func toArray<T>(ofType: T.Type) -> [T] { var array = [T]() for result in self { if let result = result as? T { array.append(result) } } return array }

let tracks = Track.allObjects().toArray(Track.self) // tracks is of type [Track]

like image 45
yong ho Avatar answered Oct 06 '22 19:10

yong ho