我遇到了 SwiftData 的问题,这肯定很简单,但我无法解决它 😢。
我有一个文件
movies.store
,其中包含大约 3k 部电影的列表,并且只有一个 Movie 实体。问题是,除了该模型之外,我还在应用程序中创建了一个@Model Favorite
来保存最喜欢的电影。我已将 movies.store
文件从捆绑包复制到文档目录,否则我可以在会话之间保留收藏夹。目前效果很好,但我需要一个解决方案来将收藏夹与电影分开,因为也许下一个版本会附带更新movies.store
,并且我需要能够替换 .store 文件,而不会对存储的收藏夹产生副作用。
我的电影列表可能是只读的,因为我只需要它来填充 ListView。收藏夹必须可读/可写。也许像将
Movie
实体保留在 movie.store 文件中并将 Favorite
保留在自己的文件中,idk。
这就是我的应用程序类的样子。有什么建议吗?
@main
struct MoviesApp: App {
var modelContainer: ModelContainer = {
guard let storeURL = Bundle.main.url(forResource: "movies", withExtension: "store") else {
fatalError("Failed to find movies.store in app Bundle")
}
do {
let fileManager = FileManager.default
let documentDirectoryURL = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let documentURL = documentDirectoryURL.appendingPathComponent("movies.store")
// Only copy the store from the bundle to the Documents directory if it doesn't exist
if !fileManager.fileExists(atPath: documentURL.path) {
try fileManager.copyItem(at: storeURL, to: documentURL)
}
let config = ModelConfiguration(url: documentURL)
return try ModelContainer(for: Movie.self Favorite.self, configurations: config)
} catch {
fatalError("Could not create ModelContainer: \(error)")
}
}()
var body: some Scene {
WindowGroup {
MainView()
}
.modelContainer(modelContainer)
}
}
我认为你需要创建两个不同的
ModelConfiguration
。一个用于保存您的电影的数据存储,一个用于保存您的收藏夹的数据存储,然后在创建 ModelContainer
时将它们组合起来:
var modelContainer: ModelContainer = {
guard let storeURL = Bundle.main.url(forResource: "movies", withExtension: "store") else {
fatalError("Failed to find movies.store in app Bundle")
}
do {
let fileManager = FileManager.default
let documentDirectoryURL = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let documentURL = documentDirectoryURL.appendingPathComponent("movies.store")
// Only copy the store from the bundle to the Documents directory if it doesn't exist
if !fileManager.fileExists(atPath: documentURL.path) {
try fileManager.copyItem(at: storeURL, to: documentURL)
}
let movieConfig = ModelConfiguration(schema: Schema([Movie.self]), url: documentURL)
let favoritesConfig = ModelConfiguration(for: Favorite.self)
return try ModelContainer(for: Movie.self, Favorite.self, configurations: movieConfig, favoritesConfig)
} catch {
fatalError("Could not create ModelContainer: \(error)")
}
}()
我更改的关键行是:
let movieConfig = ModelConfiguration(schema: Schema([Movie.self]), url: documentURL)
let favoritesConfig = ModelConfiguration(for: Favorite.self)
return try ModelContainer(for: Movie.self, Favorite.self, configurations: movieConfig, favoritesConfig)
您可能需要考虑如何处理收藏夹和电影之间的关系,并进行一些测试。