1. 添加 iCloud 功能并启用 CloudKit
在 Xcode 中打开目标的 Signing & Capabilities,点 + Capability 添加 iCloud。勾选 CloudKit,然后在 Containers 下添加或选择一个容器(标识符以 iCloud. 开头)。iCloud 功能需要有管理员权限的开发者账号。
SwiftData 要通过 iCloud 同步,Apple 的规则是:不能有唯一约束(@Attribute(.unique) 或 #Unique),所有关系都必须可选并有反向关系,不能用 .deny 删除规则。负责同步的 Core Data 还会拒绝加载这样的存储:某个属性不是可选的,声明处也没有默认值。在下方粘贴你的 @Model 类,即可看到每个问题、对应的 Apple 页面和修改后的代码行。检查器下方是 Apple 列出的设置步骤(带 CloudKit 容器的 iCloud、Background Modes 中的 Remote notifications、ModelConfiguration 的 cloudKitDatabase),代码可直接复制。
粘贴一个或多个 SwiftData 模型类。检查在本页内完成,不上传任何内容。
在上方粘贴 @Model 类,即可看到哪些地方会让它们无法通过 iCloud 同步。
SwiftData 的同步与 Core Data 使用同一套 CloudKit 机制,所以 Core Data 的规则同样适用。
来自 Apple 关于同步 SwiftData 模型数据的文章。代码是 Apple 的示例,请换成你自己的容器标识符和模型类型。 SwiftData:Syncing model data across a person's devices
在 Xcode 中打开目标的 Signing & Capabilities,点 + Capability 添加 iCloud。勾选 CloudKit,然后在 Containers 下添加或选择一个容器(标识符以 iCloud. 开头)。iCloud 功能需要有管理员权限的开发者账号。
添加 Background Modes 功能并勾选 Remote notifications。服务器上的数据变化时,CloudKit 会发送静默通知,SwiftData 据此拉取这些更改。
默认情况下,SwiftData 使用 entitlements 中列出的第一个 CloudKit 容器。如需自己指定,用 cloudKitDatabase 传入:
let config = ModelConfiguration(cloudKitDatabase: .private("iCloud.com.example.Trips"))
let modelContainer = try ModelContainer(for: Trip.self, Accommodation.self,
configurations: config)如果 App 已经把 CloudKit 用在别处,而这些模型只应保存在设备上,传入 .none:
let config = ModelConfiguration(cloudKitDatabase: .none)
let modelContainer = try ModelContainer(for: Trip.self, Accommodation.self,
configurations: config)Apple 的示例只在 Debug 构建中初始化 CloudKit 开发架构,然后再打开 SwiftData 容器。完成后在 CloudKit Console 中查看结果。
let config = ModelConfiguration()
do {
#if DEBUG
// Use an autorelease pool to make sure Swift deallocates the persistent
// container before setting up the SwiftData stack.
try autoreleasepool {
let desc = NSPersistentStoreDescription(url: config.url)
let opts = NSPersistentCloudKitContainerOptions(containerIdentifier: "iCloud.com.example.Trips")
desc.cloudKitContainerOptions = opts
// Load the store synchronously so it completes before initializing the
// CloudKit schema.
desc.shouldAddStoreAsynchronously = false
if let mom = NSManagedObjectModel.makeManagedObjectModel(for: [Trip.self, Accommodation.self]) {
let container = NSPersistentCloudKitContainer(name: "Trips", managedObjectModel: mom)
container.persistentStoreDescriptions = [desc]
container.loadPersistentStores {_, err in
if let err {
fatalError(err.localizedDescription)
}
}
// Initialize the CloudKit schema after the store finishes loading.
try container.initializeCloudKitSchema()
// Remove and unload the store from the persistent container.
if let store = container.persistentStoreCoordinator.persistentStores.first {
try container.persistentStoreCoordinator.remove(store)
}
}
}
#endif
modelContainer = try ModelContainer(for: Trip.self, Accommodation.self,
configurations: config)
} catch {
fatalError(error.localizedDescription)
}上架前在 CloudKit Console 中把开发架构发布到生产环境。此后只能新增模型类型和属性。
Apple 官方页面,查阅日期 2026 年 11 月 1 日: