Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiating Realm database for Swift 2.0 - best practice?

Tags:

realm

swift2

I'm wondering what the best practice for instantiating a Realm database is for Swift 2. One of the major differences between Realm for Swift 1.2 and Swift 2 is that the Realm class has added support for error handling. Therefore, this code on the Realm website does not work anymore:

let realm = Realm()

I can think of a couple ways to instantiate a Realm class in the Swift 2 world:

(1) let realm = try! Realm()

This option seems a little "unsafe" to me as it potentially results in a runtime error if the class fails to instantiate.

(2) Place entire Realm operation (including class instantiation) inside Do-Catch block

do {
    let realm = try Realm()

    realm.write{realm.add(myObject)}
    }
    catch
    {
        print("Some Realm error")
    }

This definitely works and is definitely safe. HOWEVER, I don't really like having to instantiate the Realm class every time I need to perform an operation on the database. If I try to create an IVAR 'realm' and place it outside of the Do-Catch block, the variable goes out of scope. For instance, the following code will not compile...

    //IVAR declared outside of Do-Catch...
    let realm:Realm

    do{
        //Get instance of Realm
        realm = try Realm()

        //This write operation works
        realm.write{realm.add(myObject_1)}
    }
    catch
    {
        print("Some Realm error")
    }


    //Create another Dog object
    let myObject_2 = SomeObject()

    //This next line produces an error:  "Variable 'realm' used before being initialized".
    //Initialized 'realm' inside Do-Catch is now out of scope.
    realm.write({
        realm.add(myObject_2)
    })

I'd appreciate any feedback (especially someone from Realm) on what the best practice for working with Realms in the new error handling environment of Swift 2 should look like. Thanks in advance.

like image 762
luckman777 Avatar asked Aug 26 '15 05:08

luckman777


2 Answers

Unless you're actually going to handle the errors you receive, I highly recommend using try!.

Your second code snippet doesn't work because, if initializing the Realm fails, that realm variable is never assigned to, which is invalid. You could probably work around that by making the realm variable be of type Realm?.

like image 182
segiddins Avatar answered Oct 31 '22 11:10

segiddins


Keep in mind that both Realm() and write can throw. That means both of them need try catch unless you use try!. Like this:

    do {
        let realm = try Realm()

        do {
            try realm.write {
                realm.add(myObject_1)
            }
        } catch let error {
            print(error)
        }

    } catch let error{

        print(error)
    }
like image 25
fisher Avatar answered Oct 31 '22 12:10

fisher