How to move Core Data database to AppGroup folder

Issue #938 To let app and extension to talk to the same database, we need to use AppGroup. Here is how to use replacePersistentStore Replaces one persistent store with another actor DatabaseMigrator { @AppStorage("DatabaseMigrator.hasMigrated") var hasMigrated = false func migrateIfNeeded() { guard !hasMigrated else { return } migrate() hasMigrated = true } private func migrate() { let oldContainer = NSPersistentCloudKitContainer(name: "Bookmarks") guard let oldStoreUrl = oldContainer.persistentStoreDescriptions.first?.url, let newStoreUrl = Constants.appGroup.folderUrl?.appendingPathComponent(oldContainer.name + "....

July 30, 2023 · 1 min · 183 words · Khoa

Composition in Realm

Issue #13 There is time we have models that have some kind of inheritance, like Dog, Cat, Mouse can be Animal. We can use composition to imitate inheritance, we just need to make sure it has unique primary key Cat and Dog These are pretty much basic Realm objects class Dog: Object { dynamic var id: Int = 0 required convenience init(json: [String: Any]) { self.init() id <- json.integer(key: "id") } } class Cat: Object { dynamic var id: Int = 0 required convenience init(json: [String: Any]) { self....

May 2, 2017 · 1 min · 177 words · Khoa

Primary key in Realm

Issue #4 Realm is great. But without primary key, it will duplicate the record, like https://github.com/realm/realm-java/issues/2730, http://stackoverflow.com/questions/32322460/should-i-define-the-primary-key-for-each-entity-in-realm, … So to force ourselves into the good habit of declaring primary key, we can leverage Swift protocol Create primary constrain protocol like this protocol PrimaryKeyAware { var id: Int { get } static func primaryKey() -> String? } and conform it in out Realm object class Profile: Object, PrimaryKeyAware { dynamic var firstName: String = "" dynamic var lastName: String = "" dynamic var id: Int = 0 override static func primaryKey() -> String?...

April 26, 2017 · 1 min · 164 words · Khoa