Код: Выделить всё
@ModelActor
actor ItemDataSource {
func fetch() -> [UserEntity] {
do {
return try modelContext.fetch(FetchDescriptor())
} catch {
fatalError(error.localizedDescription)
}
}
func append(user: UserEntity) {
modelContext.insert(user)
do {
try modelContext.save()
} catch {
fatalError(error.localizedDescription)
}
}
func delete() {
do {
try modelContext.delete(model: UserEntity.self)
try modelContext.save()
} catch {
fatalError(error.localizedDescription)
}
}
}
Код: Выделить всё
private let dataSource = ItemDataSource(modelContainer: try! ModelContainer(for: UserEntity.self))
Код: Выделить всё
class GithubViewModel: ObservableObject {
private let dataSource: ItemDataSource
private let networkService: NetworkService
@Published var viewState: ViewState = .loading
@Published var users: [UserEntity] = []
init(networkService: NetworkService, dataSource: ItemDataSource) {
self.networkService = networkService
self.dataSource = dataSource
refresh()
}
Код: Выделить всё
struct ContentView: View {
@ObservedObject var viewModel: GithubViewModel
Код: Выделить всё
#Preview {
@State var navigationPath = [NavigationPath]()
return ContentView(viewModel: GithubViewModel(networkService: NetworkService(), dataSource: ItemDataSource()), navigationPath: $navigationPath)
}
Исходный код можно найти: https: //github.com/alirezaeiii/CachingSwiftData
Подробнее здесь: https://stackoverflow.com/questions/792 ... -parameter
Мобильная версия