Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS (Swift) Singleton Realm Object

After reading this tutorial I need some assistance in understanding what the most efficient way to do the following.

When my app is opened, it needs to load a Profile object. Since there should only be one of these in the lifetime of the app I set it up to be a singleton.

Realm seemed to be a great way to save and retrieve data. Upon further viewing it seems I need to have a data model in order to use Realms. After a failed attempt of integrating Object into the Profile.swift shown below I need some assistance in how I should handle this issue. Should I make a second class ProfileDataModel that can be called by Profile to retrieve and save changes, or is there a way to include a Realm Object into a Singleton class?

Profile.swift

class Profile {

    //MARK: Singleton
    static let sharedInstance = Profile()

    //MARK: Properties
    var characterName: String
    var level: Int

    //MARK: Init
    private init() {
        //TODO: Load from realms
        self.characterName = "John Appleseed"
        self.level = 50
    }

    //MARK: Helper Methods
    static func save(){
        //TODO: Save to Realm
    }
}
like image 445
Austin E Avatar asked Jul 03 '16 02:07

Austin E


1 Answers

I suggest you to create a db manager class to handle all db operations on it, then you can create your data models separately and use your manager class to fetch/store data on your db.

class DBManager {
//MARK: Singleton
static let sharedInstance = DBManager()

//MARK: Init
private override init(){
    let config = Realm.Configuration(
        fileURL: dbPath,
        readOnly: false)
    do{
        myDB = try Realm(configuration: config)
        print(dbPath)
    }
    catch{
        print("boooom")
    }

}

    //retrive data from db
    func getDataFromDB() -> Results<DataModel>{
    let results: Results<NewsModel> = myDB.objects(DataModel)
    return results
    }

    //write an object in db
    func addDataModelEntry(object: DataModel){
        try! myDB.write{
            myDB.add(object, update: true)
        }
    }

}

//your controller you want to use your db manager class
class main(){ 
    func viewDidLoad(){
       DBManager.sharedInstance.getDataFromDB() ///here you have realm results

       DBManager.sharedInstance.addDataModelEntry(customDataModel) //to store your object on db
    }
}

i put some samples just to show the way of doing, you can use these functions to extend to any kind of db operations for your specific needs.

like image 176
sbsr Avatar answered Sep 21 '22 02:09

sbsr