Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all objects of a class in Realm to an array

Tags:

swift

realm

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.

like image 361
JDG Avatar asked Aug 02 '15 03:08

JDG


2 Answers

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).

like image 148
User Avatar answered Sep 20 '22 05:09

User


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)

    }
}
like image 42
Rikesh Subedi Avatar answered Sep 17 '22 05:09

Rikesh Subedi