Onappear引起了预览的问题,但没有显示错误

发布于 2025-01-26 03:47:56 字数 2368 浏览 2 评论 0原文

自我学习初学者。

当我删除.onappear {add()}时,预览效果很好。我试图将其连接到其他视图,即VSTACK,但会导致另一个错误。我阅读/观看了几个教程,但没有提到任何内容。...

任何帮助都得到赞赏

struct ListView: View {

@Environment(\.managedObjectContext) var moc
@FetchRequest(sortDescriptors: []) var targets: FetchedResults<TargetEntity>
@FetchRequest(sortDescriptors: []) var positives: FetchedResults<PositiveEntity>

var body: some View {
    
    VStack {
        Text("+")
        .onAppear{add()} 
        .onTapGesture (count: 2){
            do {
                increment(targets.first!) //I also sense that doing "!" is not good.  But it's the only way I can keep it from causing error "Cannot convert value of type 'FetchedResults' to expected argument type 'X'"
                try moc.save()
            } catch {
                print("error")
            }
        }
    }
}
    
func increment(_ item: TargetEntity) {
        item.countnum += 1
        save()
}

func add() {
    let countnum = TargetEntity(context: moc)
    countnum.countnum = 0
    save()
}

func save() {
    do { try moc.save() } catch { print(error) }
}

}

“在此处输入图像说明”

编辑20220509: 正如@YRB的建议(非常感谢),错误可能是由于缺乏持久文件中预览VAR的适当设置而引起的。我在此处发布相关代码以进行Visiblity。

数据控制器文件

import CoreData
import Foundation

class DataController: ObservableObject {
    let container = NSPersistentContainer(name: "CounterLateApr")
    
    init () {
        container.loadPersistentStores { description, error in
            if let error = error {
                print("Core Data failed to load: \(error.localizedDescription)")
            }
        }
    }
}

预览代码在视图

struct ListView_Previews: PreviewProvider {
    static var previews: some View {
        NavigationView{
            ListView()
        }        
    }
}

[appName] .app文件中

import SwiftUI

@main
struct CounterLateAprApp: App {
    
    @StateObject private var dataController = DataController()
    
    var body: some Scene {
        WindowGroup {
            ContentView()
                .environment(\.managedObjectContext, dataController.container.viewContext)
        }
    }
}

self learning beginner here.

When I remove .onAppear{add()}, the preview works fine. I tried to attach it to other the body view, the Vstack but it causes another error. I read/watched several tutorials but nothing like this is mentioned....

Any help is appreciated

struct ListView: View {

@Environment(\.managedObjectContext) var moc
@FetchRequest(sortDescriptors: []) var targets: FetchedResults<TargetEntity>
@FetchRequest(sortDescriptors: []) var positives: FetchedResults<PositiveEntity>

var body: some View {
    
    VStack {
        Text("+")
        .onAppear{add()} 
        .onTapGesture (count: 2){
            do {
                increment(targets.first!) //I also sense that doing "!" is not good.  But it's the only way I can keep it from causing error "Cannot convert value of type 'FetchedResults' to expected argument type 'X'"
                try moc.save()
            } catch {
                print("error")
            }
        }
    }
}
    
func increment(_ item: TargetEntity) {
        item.countnum += 1
        save()
}

func add() {
    let countnum = TargetEntity(context: moc)
    countnum.countnum = 0
    save()
}

func save() {
    do { try moc.save() } catch { print(error) }
}

}

enter image description here

EDIT 20220509:
As advised by @Yrb (great thanks), the error is likely caused by the lack of a proper set up of preview var in the persistence file. I post the relevant code here for visiblity.

Data Controller file

import CoreData
import Foundation

class DataController: ObservableObject {
    let container = NSPersistentContainer(name: "CounterLateApr")
    
    init () {
        container.loadPersistentStores { description, error in
            if let error = error {
                print("Core Data failed to load: \(error.localizedDescription)")
            }
        }
    }
}

preview code in a view

struct ListView_Previews: PreviewProvider {
    static var previews: some View {
        NavigationView{
            ListView()
        }        
    }
}

[AppName].app file

import SwiftUI

@main
struct CounterLateAprApp: App {
    
    @StateObject private var dataController = DataController()
    
    var body: some Scene {
        WindowGroup {
            ContentView()
                .environment(\.managedObjectContext, dataController.container.viewContext)
        }
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文