Design Pattern for Realm Database Swift 3.1 - Singleton

时光总嘲笑我的痴心妄想 提交于 2019-12-10 00:47:48

问题


I'm working on RealmSwift, which is a modern database replacement of CoreData/SQLite in Swift.

I'm wondering how to implement a design for a Class which can manage/handle all the queries for RealmSwift Framework

This question is somewhat similar to implementing SQLite Model Manager but for RealmSwift.

Specifically I don't require a singleton object/instance mention above.


回答1:


Realm has a rather clever internal caching system where previous instances of Realm are held onto and recycled each time a call like let realm = try! Realm() occurs. As such, it's not really necessary, nor recommended to try and incorporate a Realm instance itself into a singleton.

If you want to heavily customise your Realm instance's settings, you'll normally do that through a Realm Configuration object, which is static and thread-safe. If that's the case, it would be more appropriate to have a singleton (or even just a static class method) that returns the appropriate Configuration object when you need to create a new Realm instance.

that thing in swift has a page on how to create singletons in Swift, and it's essentially just a single static property of a class implementation:

class SomeManager {
    static let sharedInstance = SomeManager()
}



回答2:


Use an enum with one case:

enum Singleton: Protocols {
    case instance
    /// methods
}

Used like:

Singleton.instance.method(args)


来源:https://stackoverflow.com/questions/36145771/design-pattern-for-realm-database-swift-3-1-singleton

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