我正在构建一个简单的应用程序,它使用 SwiftData 框架保存数据,并具有通过 CloudKit 跨设备同步的附加功能。
一切都很顺利,直到我添加了第二个模型对象。两个模型之间没有关系,但简单添加一个新对象会导致应用程序在创建
ModelContainer
时抛出错误。
有人知道如何正确执行此操作吗? 这是一些代码来说明相关的(我认为)部分......
首先是主应用程序文件...
import SwiftUI
import SwiftData
@main
struct FeederApp: App {
var sharedModelContainer: ModelContainer = {
let feedSchema = Schema([Feed.self])
let noteSchema = Schema([Note.self])
let feedModelConfiguration = ModelConfiguration("default", schema: feedSchema, isStoredInMemoryOnly: false)
let noteModelConfiguration = ModelConfiguration("NoteConfiguration", schema: noteSchema, isStoredInMemoryOnly: false)
do {
return try ModelContainer(for: Feed.self, Note.self, configurations: feedModelConfiguration, noteModelConfiguration)
} catch {
//TODO: add some error correction
fatalError("Could not create ModelContainer: \n\(error)") //ERROR HERE
}
}()
var body: some Scene {
WindowGroup {
ContentView()
.foregroundStyle(.green)
}
.modelContainer(sharedModelContainer)
}
}
这是模型对象...
import Foundation
import SwiftData
enum Source: String, Codable, CaseIterable, Identifiable, Equatable {
case formula_standard = "Formula"
case formula_enriched = "Formula Enriched"
case breast = "Breast Milk"
var id: Self { self }
}
@Model
final class Feed {
var timestamp: Date = Date.now
var source: Source = Source.breast
var qty_as_int: Int = 0
var id = UUID()
init(timestamp: Date, qty_as_int: Int, source: Source) {
self.timestamp = timestamp
self.source = source
self.qty_as_int = qty_as_int
}
}
还有新型号...
import Foundation
import SwiftData
enum WeightType: String, Codable, CaseIterable, Identifiable, Equatable{
case weight = "Standard Weighing"
case birthWeight = "Birth Weight"
var id: Self { self }
}
@Model
final class Weight: Identifiable {
var id = UUID()
var weight: Double
var date: Date = Date()
var type: WeightType = WeightType.weight
init(weight: Double,
type: WeightType) {
self.weight = weight
self.type = type
}
init(weight: Double,
type: WeightType,
date: Date) {
self.weight = weight
self.type = type
self.date = date
}
}
这是错误:
Feeder/FeederApp.swift:24: Fatal error: Could not create ModelContainer: SwiftDataError(_error: SwiftData.SwiftDataError._Error.loadIssueModelContainer, _explanation: nil)
我是否需要在 CloudKit 仪表板中手动为新模型对象添加新架构?
如果我将 CloudKit 数据库设置为
.none
,那么应用程序会运行,但当然不会跨设备同步新模型对象。
由于我有一个可使用 iCloud 同步的应用程序(使用单个“默认”数据存储),因此我只需添加新的
Weight
模型类型并更新我的容器初始化以包含它。
modelContainer = try ModelContainer(for: Entry.self, Weight.self, configurations: configuration)
启动应用程序崩溃并出现以下错误:
CloudKit integration requires that all attributes be optional, or have a default value set. The following attributes are marked non-optional but do not have a default value:
Weight: weight
这告诉我们,您对
Weight
的定义与 CloudKit 不兼容。 (查看 Apple 文档中的定义 CloudKit 兼容架构。
修复了
Weight
的定义,使其具有默认值 属性 weight
修复了应用程序启动问题。
@Model
final class Weight: Identifiable {
var id = UUID()
var weight: Double = 0.0
var date: Date = Date()
var type: WeightType = WeightType.weight
}
为了测试,我添加了一个按钮来添加
Weight
模型...它会自动同步到 CloudKit!