iOS (Swift) Singleton Realm Object

前提是你 提交于 2019-12-12 08:10:12

问题


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
    }
}

回答1:


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.




回答2:


As you already suggested, it wouldn't be a very good idea to implement the Singleton pattern on a Realm managed object. These are bound to a thread and can be only modified from write transactions.

Instead if you need shared mutable global state and want to persist that within Realm, I'd recommend to have a class which allows you to retrieve objects, which only act in the purpose of describing the persisted data. E.g. a DatabaseManager as a singleton, which instantiates a new Realm and returns the single existing Profile object, inheriting from Object but without custom static properties or methods.



来源:https://stackoverflow.com/questions/38166276/ios-swift-singleton-realm-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!