Hayden
Hayden

Reputation: 1870

Best way to store a single instance of RLMObject

I'm currently developing an iOS app with Realm as the backend data storage. I have a class that is an RLMObject for the user profile. It stores their name, profile picture, stats, etc.

There should only always be one of these objects, however I know implementing a singleton pattern is usually a bad idea. Currently I have it implemented as

//AppDelegate.swift, applicationDidFinishLaunching
//If there's no user profiles yet (first time launch), create one

if UserProfile.allObjects().count == 0 {
    let realm = RLMRealm.defaultRealm()
    try! realm.transactionWithBlock() {
        realm.addObject(UserProfile())
    }
}


//ProfileViewController.swift
//Get the first UserProfile
var userProfile: UserProfile? {
        get { 
            return UserProfile.allObjects().objectAtIndex(0) as? UserProfile 
        }
}

Is there a better way to keep track of a single instance of this class?

Upvotes: 1

Views: 319

Answers (1)

AustinZ
AustinZ

Reputation: 1787

Your code sample uses a computed property, which will fetch the object from the Realm each time you access it.

Instead, try using a lazy var property:

lazy var userProfile: UserProfile? = { 
    return UserProfile.allObjects().objectAtIndex(0) as? UserProfile 
}()

This type of property will load the object from the Realm only the first time it is accessed. All subsequent accesses will be directly to the object.

Note that, since UserProfile is a Realm object, its fields will automatically update in response to changes made to the underlying object in the Realm. Likewise, any changes you wish to make will need to be wrapped within a Realm write transaction.

In terms of your overall architecture, there is nothing wrong with storing a single instance of an object type in a Realm similar to what you are doing. You may want to give your UserProfile object a hardcoded constant primary key, then use the 'add or update' version of the update API (see https://realm.io/docs/swift/latest/#updating-objects). This will allow you to avoid having to explicitly create a new object.

Upvotes: 1

Related Questions