Realm migration succeeds when app is offline but when becomes online, local objects are replaced with iCloud objects causing local objects lose data

60 views Asked by At

I am using IceCream library for syncing Realm with iCloud. I need to do realm migration for my next version. The migration succeeds when the app is offline. but on becoming online, when iCloud records are fetched, local object lose "phoneNumber" property. Objects detail is given below.

I had recipient and phonenumber objects like these.


    @objc class Recipient: Object {
    @persisted(primaryKey: true) var rec_id = ""
    @persisted var firstName = ""
    @persisted var lastName = ""
    @persisted var phoneNumbersList = List()
    @persisted var email = ""
    @persisted var isDeleted = false // IceCream requirement
    }

    @objc class PhoneNumber: Object {
    @persisted(primaryKey: true) var id = ""
    @persisted var number = ""
    @persisted var isDeleted = false // IceCream requirement
    }

I changed the schema to this. i.e. removed the phoneNumberList property and added phoneNumber as string only.


    @objc public class Recipient: Object {
    @persisted(primaryKey: true) var rec_id = ""
    @persisted var firstName = ""
    @persisted var lastName = ""
    @persisted var phoneNumber = ""
    @persisted var email = ""
    @persisted public var isDeleted = false // IceCream requirement
    }

Old records on icloud have phoneNumberList property populated and phoneNumber property is nil.

Now in the new version of the app, i have done migration correctly and it works but when the app is offline. When it becomes online, the migrated records again are replaced with the fetched records from icloud whose phoneNumber property is nil and my app starts missing phoneNumbers. How can i solve this?

1

There are 1 answers

1
Jay On

This line

@persisted var phoneNumbersList = List()

needs to be updated to this if the intent is to store PhoneNumber objects in Realm

@persisted var phoneNumbersList = RealmSwift.List<PhoneNumber>()

There are several reason: using this RealmSwift.List will tell the compiler to use the RealmSwift List object instead of the SwiftUI List object. Then this List() is not a Realm descriptor or assignment which is why it 'looses data' as it's not managed by Realm.

I would also advise allowing objects to self populate the primary key like this

@Persisted(primaryKey: true) var _id: ObjectId

leaving it empty "" can cause issues if you forget to populate it.