我理解你的问题。 这里的守则表明如何用核心数据和云基实现衍生特性:
import CoreData
import CloudKit
// Assuming you have List and Item entities with a one-to-many relationship
// List entity
class List: NSManagedObject {
@NSManaged var items: Set<Item>
@NSManaged var itemCount: Int16
@NSManaged var itemSum: Double
}
// Item entity
class Item: NSManagedObject {
@NSManaged var value: Double
}
// In your CoreData stack setup, enable history tracking
let description = NSPersistentStoreDescription()
description.cloudKitContainerOptions = NSPersistentCloudKitContainerOptions(containerIdentifier: "your.container.id")
description.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)
// Whenever you update related Item records in Core Data, recalculate derived attributes
func updateDerivedAttributes(for list: List) {
let itemCount = list.items.count
let itemSum = list.items.reduce(0.0, { $0 + $1.value })
list.itemCount = Int16(itemCount)
list.itemSum = itemSum
// Save your managedObjectContext to persist changes
}
// CloudKit subscription to monitor changes and trigger updates
let subscription = CKQuerySubscription(recordType: "List", predicate: NSPredicate(value: true), options: .firesOnRecordCreation)
let notificationInfo = CKSubscription.NotificationInfo()
notificationInfo.shouldSendContentAvailable = true
subscription.notificationInfo = notificationInfo
// Add the subscription to your CloudKit database
let container = CKContainer(identifier: "your.container.id")
let database = container.privateCloudDatabase
database.save(subscription) { subscription, error in
// Handle subscription save completion
}
铭记利用云基的衍生特性,可能会带来复杂情况,特别是在yn和冲突方面。 你可能需要认真管理更新,以避免过度的冲突。 采用<代码>NSPersistentHistoryTrackingKey的做法可以发挥作用,但如果经常更新,则可能确实导致冲突。 必要时考虑采用解决冲突的战略。