CloudKit:防止重复记录 [英] CloudKit: Preventing Duplicate Records

查看:179
本文介绍了CloudKit:防止重复记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个应用程序,将外部Web服务中的数据提取到私有CloudKit数据库中。该应用程序是一个单用户应用程序,但我遇到了竞争条件,我不知道如何避免。

I am working through an app that pulls data from an external web service into a private CloudKit database. The app is a single user app, however I am running into a race condition that I am not sure how to avoid.

我的外部数据中的每条记录都有一个唯一的标识符,我映射到我的CKRecord实例。一般应用启动流程为:

Every record in my external data has a unique identifier that I map to my CKRecord instances. The general app startup flow is:


  1. 获取相关记录类型的当前CKRecords。

  2. 获取外部记录。

  3. 对于每个外部记录,如果CloudKit中不存在,则通过批量创建(修改操作)创建它。

现在问题是,如果这个过程同时在用户的两个设备上启动,那么CK和外部提取都是如此是非同步的,很有可能我会得到重复的记录。

Now, the issue is, if this process is kicked off on two of a user's devices simultaneously, since both the CK and external fetch is async, there is a strong possibility that I'll get duplicate records.

我知道我可以使用区域以原子方式提交我所有的CKRecord实例,但我不知道我认为这解决了我的问题,因为如果所有这些提取同时发生,那么保存并不是真正的问题。

I know I can use zones to atomically commit all of my CKRecord instances, but I don't think that solves my issue because if all of these fetches happen at essential the same time, the save is not really the issue.

我的问题是:


  1. 有没有人知道如何锁定 用于在所有用户设备上写入的私有数据库?

  2. 或者,有没有办法在任何CKRecord字段上强制执行唯一性?

  3. 或,有没有办法使用自定义值作为主键,在这种情况下,我可以使用我的外部ID作为CK ID,并允许系统自己防止重复。

感谢您提前获得帮助!

推荐答案

答案:



Answers:


  1. 不,你无法锁定私人数据库

  2. Cloudkit已经强制执行并假定您的记录ID的唯一性

  3. 您可以将记录ID设置为您喜欢的任何内容(在非区域部分)。



说明:



关于复制问题。如果您是创建记录ID的人(例如,您提到的外部记录),那么在最坏的情况下,如果您有竞争条件,则应该有一个记录,而不是使用相同的数据写另一个记录。我不认为这是一个极端情况下两个设备同时启动此过程的问题。基本上你首先获取现有记录然后修改它们的逻辑对我来说似乎是合理的。

Explanation:

Regarding your issue of duplication. If you are the one creating the record IDs (from the external records you mentioned for example) then at worst you should have one record over write the other with the same data if you have a race condition. I do not think that is an issue for the extreme case two devices kick off this process at the same time. Basically you logic of first fetching existing records and then modifying them seems sound to me.

//employeeID is a unique ID to identify an employee
let employeeID = "001"

//Remember the recordID needs to be unique within the same database.
//Assuming you have different record types, it is better to prefix the record name with the record type so that it is unique
let recordName = "Employee-\(employeeID)"

//If you are using a custom zone
let customZoneID = CKRecordZoneID(zoneName: "SomeCustomZone", ownerName: CKCurrentUserDefaultName)
let recordIDInCustomZone = CKRecordID(recordName: recordName, zoneID: customZoneID)

//If you are using the default zone
let recordIDInDefaultZone = CKRecordID(recordName: recordName)

这篇关于CloudKit:防止重复记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆