Currently I am using this:
var matchedUsersFromRealm = MatchedUser.allObjects()
var matchedUsersInRealm = RLMArray(objectClassName: MatchedUser.className())
matchedUsersInRealm.removeAllObjects()
matchedUsersInRealm.addObjects(matchedUsersFromRealm)
But it just looks cumbersome rather than just getting it in one line as it should (or did?). Maybe there is a better way?
PS, I am working on a mix project and somehow I can only use the Objective-C version and bridge it to my swift project. So the Realm().objects() is not available, even though it returns a Results not an array.
You can add these extensions:
import Foundation
import RealmSwift
extension Results {
func toArray() -> [T] {
return self.map{$0}
}
}
extension RealmSwift.List {
func toArray() -> [T] {
return self.map{$0}
}
}
And then when fetching:
do {
let realm = try Realm()
let objs = realm.objects(MyObjType).toArray()
// ...
} catch _ {
// ...
}
(Remove do try catch if you're using Swift pre-2.0)
Note that this loads everything into memory at once, which may be in some cases not desired. If you're fetching in the background, it's required though, as Realm currently doesn't support using the objects in the main thread after that (you will also have to map the array to non-Realm objects in this case).
I preferred to add a helper class to save and retrieve any type of objects using Generics.
class RealmHelper {
static func saveObject<T:Object>(object: T) {
let realm = try! Realm()
try! realm.write {
realm.add(object)
}
}
static func getObjects<T:Object>()->[T] {
let realm = try! Realm()
let realmResults = realm.objects(T.self)
return Array(realmResults)
}
static func getObjects<T:Object>(filter:String)->[T] {
let realm = try! Realm()
let realmResults = realm.objects(T.self).filter(filter)
return Array(realmResults)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With