默认情况下,不允许使用constraint,取消后,需要代码处理,不然会出现数据重复;经过一番折腾,找到了个简单办法,本地Entity可以继续使用constraint, 与大家分享。

第一步:新建Model Configuration

选中Model文件, 通过Editor -> Add Configuration菜单,新建Local和Cloud两个Configuration,把需要同步的Entity拖入Cloud,本地使用的Entity拖到Local;

国内使用cloudflare有效果吗(4在使用CloudKit后)(1)

image.png

对Cloud Configuration,选中Used with CloudKit选荐

国内使用cloudflare有效果吗(4在使用CloudKit后)(2)

image.png

第二步:修改Persistence中的container配置

var container: NSPersistentCloudKitContainer = { let container = NSPersistentCloudKitContainer(name: "AAStock") // 1. 注意:与实际保持一致 let storeDirectory = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first! // 2. 获取文件位置 // Create a store description for a local store let localStoreLocation = storeDirectory.appendingPathComponent("local.sqlite") // 3. 为Local配置添加Store let localStoreDescription = NSPersistentStoreDescription(url: localStoreLocation) localStoreDescription.configuration = "Local" // Create a store description for a CloudKit-backed local store let cloudStoreLocation = storeDirectory.appendingPathComponent("cloud.sqlite") // 4. 为Cloud配置添加Store let cloudStoreDescription = NSPersistentStoreDescription(url: cloudStoreLocation) cloudStoreDescription.configuration = "Cloud" // Set the container options on the cloud store cloudStoreDescription.cloudKitContainerOptions = NSPersistentCloudKitContainerOptions( containerIdentifier: "iCloud.com.tang.AAStock") // 5. 注意保持CloudKit container一致 // Update the container's list of store descriptions container.persistentStoreDescriptions = [ cloudStoreDescription, localStoreDescription ] // Load both stores container.loadPersistentStores { storeDescription, error in guard error == nil else { fatalError("Could not load persistent stores. \(error!)") } } return container }()

通过上述两步配置,可以愉快地使用constraint了,试试吧。

,