问题
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