-1.4 C
New York
Monday, January 6, 2025

ios – #Preview whereas utilizing @ModelActor as parameter


I created a ModelActor as comply with :

@ModelActor
actor ItemDataSource {
    
    func fetch() -> [UserEntity] {
        do {
            return attempt modelContext.fetch(FetchDescriptor())
        } catch {
            fatalError(error.localizedDescription)
        }
    }
    
    func append(person: UserEntity) {
        modelContext.insert(person)
        do {
            attempt modelContext.save()
        } catch {
            fatalError(error.localizedDescription)
        }
    }
    
    func delete() {
        do {
            attempt modelContext.delete(mannequin: UserEntity.self)
            attempt modelContext.save()
        } catch {
            fatalError(error.localizedDescription)
        }
    }
}

It has been handed to my ViewModel in App struct as comply with :

non-public let dataSource = ItemDataSource(modelContainer: attempt! ModelContainer(for: UserEntity.self))

And right here is my ViewModel init perform :

class GithubViewModel: ObservableObject {
    non-public let dataSource: ItemDataSource
    non-public let networkService: NetworkService
    
    @Printed var viewState: ViewState = .loading
    @Printed var customers: [UserEntity] = []
    
    init(networkService: NetworkService, dataSource: ItemDataSource) {
        self.networkService = networkService
        self.dataSource = dataSource
        refresh()
    }

ViewModel is handed to my ContentView utilizing SwiftUI :

struct ContentView: View {
    
    @ObservedObject var viewModel: GithubViewModel

Now I need to write a Preview for my ContentView. The best way to create an occasion of ItemDataSource in #Preview?

#Preview {
    @State var navigationPath = [NavigationPath]()
    return ContentView(viewModel: GithubViewModel(networkService: NetworkService(), dataSource: ItemDataSource()), navigationPath: $navigationPath)
}

The error says : 'ItemDataSource' can't be constructed as a result of it has no accessible initializers

Supply code may be discovered : https://github.com/alirezaeiii/CachingSwiftData

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles