使用 CloudKit 时如何对 Core Data 实体记录进行重复数据删除?
How to deduplicate Core Data entity records when using 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
}
由于使用 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
}