0

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.

aashish tamsya
  • 4,903
  • 3
  • 23
  • 34
  • The TL;DR duplicate for this is [Using a dispatch\_once singleton model in Swift](http://stackoverflow.com/questions/24024549/using-a-dispatch-once-singleton-model-in-swift) The bottom line is what TiM said. – David Berry Mar 22 '16 at 05:25

2 Answers2

7

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()
}
TiM
  • 15,812
  • 4
  • 51
  • 79
  • Also private init() is recommended to restrict multiple instantiations of your SomeManager class. Otherwise your class is not a real singleton. – Whirlwind Mar 22 '16 at 04:31
  • @TiM i require an implementation idea for a manage class which will be used for handling all the queries related to Realm – aashish tamsya Mar 22 '16 at 05:34
  • I have created a RealmManager class (DB manager) that has all calls dealing with realm. For example, getUserInfo, saveUserInfo. I don't allow realm to touch anything outside of this class and I use class func where I instantiate realm for each function instead of a shared realm singleton instance for the entire manager. I have run into a crazy issue where an object can be tied to a previous realm instance if I chain these functions (object is open in another realm instance). Since you can't close realm manually, would this be ok to turn it into a singleton at this point instead? – Nox Aug 23 '18 at 17:00
1

Use an enum with one case:

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

Used like:

Singleton.instance.method(args)
Howard Lovatt
  • 968
  • 1
  • 8
  • 15