Design Pattern for Realm Database Swift 3.1 - Singleton

烈酒焚心 提交于 2019-12-04 21:28:42

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

Use an enum with one case:

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

Used like:

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