如何解决使用 CloudKit 时如何删除重复的核心数据实体记录?
由于在使用 CloudKit 时无法使用唯一约束,并且将某些实体存储在 NSPersistentCloudKitContainer
中会导致在跨多个设备同步数据后出现重复记录。
是否有任何现有的最佳实践来删除存储在 CloudKit 上的核心数据实体记录的重复数据?
我将应用的当前用户对象存储在 Core Data 中,以 iCloud 用户记录 ID 作为唯一标识符;但是,在条目同步到其他设备后,User
SQLite 数据下会出现多个用户。
func getLocalUser() -> User? {
/// Try to fetch the only local user
let idMixpanel = DCMixpanel.shared.distinctId
let fetchRequest: NSFetchRequest<User> = User.fetchRequest()
let userPredicate = NSPredicate(
format: "%K = %@",#keyPath(User.idMixpanel),idMixpanel
)
fetchRequest.predicate = userPredicate
let userList = try? container.viewContext.fetch(fetchRequest)
if let user = userList?.first {
if user.idCloudKit == nil {
/// This method is async and the ID is not available immediately after function invocation
setupCloudKitUserID()
}
return user
}
/// Create a new local user if no user found with local ID
let userLocalNew = User(context: container.viewContext)
userLocalNew.idMixpanel = DCMixpanel.shared.distinctId
saveContext()
return userLocalNew
}
解决方法
我的解决方案是创建一个 mergeLocalUser
方法
private func mergeLocalUser() -> User? {
/// Fetch all users
/// Merge users if there are more than one user in the local database
/// Custom user properties merging logic
/// Delete all user instances and re-create a new user
return newUserInstance
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。