xcode iOS (Swift) 单例领域对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38166276/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 09:00:02  来源:igfitidea点击:

iOS (Swift) Singleton Realm Object

iosxcodeswiftsingletonrealm

提问by Austin E

After reading thistutorial 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 Profileobject. Since there should only be one of these in the lifetime of the app I set it up to be a singleton.

当我的应用程序打开时,它需要加载一个Profile对象。由于在应用程序的生命周期中应该只有其中一个,因此我将其设置为单例。

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 Objectinto the Profile.swift shown below I need some assistance in how I should handle this issue. Should I make a second class ProfileDataModelthat can be called by Profileto retrieve and save changes, or is there a way to include a Realm Objectinto a Singleton class?

Realm 似乎是一种保存和检索数据的好方法。进一步查看后,我似乎需要一个数据模型才能使用 Realms。在尝试集成Object到如下所示的 Profile.swift失败后,我需要一些关于如何处理此问题的帮助。我应该创建第二个ProfileDataModel可以调用的类Profile来检索和保存更改,还是有办法将 Realm 包含Object到 Singleton 类中?

Profile.swift

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

回答by Saeid Basirnia

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.

我建议你创建一个 db manager 类来处理它上的所有 db 操作,然后你可以单独创建你的数据模型并使用你的 manager 类在你的 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.

我放了一些示例只是为了展示这样做的方式,您可以使用这些函数扩展到任何类型的数据库操作以满足您的特定需求。

回答by marius

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.

正如您已经建议的那样,在 Realm 托管对象上实现单例模式并不是一个好主意。这些绑定到一个线程,只能从写入事务中修改。

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 DatabaseManageras a singleton, which instantiates a new Realm and returns the single existing Profileobject, inheriting from Objectbut without custom staticproperties or methods.

相反,如果您需要共享的可变全局状态并希望在 Realm 中保留它,我建议您拥有一个允许您检索对象的类,该类仅用于描述持久化数据的目的。例如 aDatabaseManager作为单例,它实例化一个新的 Realm 并返回单个现有Profile对象,继承自Object但没有自定义static属性或方法。