amagain
amagain

Reputation: 2072

I am trying to instantiate a Realm database for Swift 2

[I tried some of the solutions given over in stackoverflow but I am getting run time error] let realm = try! Realm() doesn't throw any error while building but once the app is running, it gives EXC_BAD_INSTRUCTION.

How can I fix the error in instantiating Realm?

Screenshot of error: Screenshot of error

Upvotes: 1

Views: 647

Answers (2)

marius
marius

Reputation: 7806

It seems like you're trying to initialize a Realm from the default value of a UIViewControlller. Be aware, if that's your initial view controller, that this might happen before your AppDelegate's application:didFinishLaunchingWithOptions: is executed, from where you might setup the default configuration. But this should happen before you initialize any accessors.

I'd recommend to use Dependency Injection to set the Realm from a later point in time, after the application launch is fully finished.

Alternatively you could instead declare your property as implicitly unwrapped optional and initialize it's value in the viewDidLoad method.

var realm: Realm!

override func viewDidLoad() {
    super.viewDidLoad()

    self.realm = try! Realm()
}

Upvotes: 3

dfrib
dfrib

Reputation: 73186

Possibly, you shouldn't define realm as a class property, but rather locally in a do-try-catch closure where you perform some realm action (say, realm.write).

Moreover, at the line of the error: if the statementlet realm = try! Realm fails, you will hit an assert which will cause that the app to crash at runtime (thanks @marius).

Instead, consider using your calls to Realm() in some class method, where you handle possible errors/asserts via the catch closure.

func TryToWriteToRealm(myText: String) {
    do {
        let realm = try Realm()
        try realm.write {
            realm.add(myText)
        }
    } catch {
        print("Error!")
        // some error handling
    }
}

Then call TryToWriteToRealm(...) when you want to e.g. Write to your realm.


For details of the difference between try, try? and try!, see e.g.

Upvotes: 1

Related Questions