你好,

Xcode 12(Beta)在创建支持CoreData时,有一些新的模板代码。
如果您的书终于解决了SWIFTUI,那将是良好的,现在它是新项目的默认值。

覆盖主题示例:

  1. 使用struct(如下所示)或coredatastack的类? (特别是在MVVM设置中,其中开奖结果3d将处理CoreData交互,而不是在视图内部利用属性包装器)
  2. 使用 @stateObject. vs. @observedobject. 对于视图中的开奖结果3d var
  3. 使用Property包装器直接在视图中,在单独的商店(AKA 开奖结果3d类)中的数据操作的MVVM处理(AKA 开奖结果3d类,或者什么人员选择调用它)。

谢谢!

1 Like

- persistenceController.swift.

导入coredata.

struct persistenceController {
静态左左侧= persistenceController()

static var preview: PersistenceController = {
    let result = PersistenceController(inMemory: true)
    let viewContext = result.container.viewContext
    for _ in 0..<10 {
        let newItem = Item(context: viewContext)
        newItem.timestamp = Date()
    }
    do {
        try viewContext.save()
    } catch {
        // Replace this implementation with code to handle the error appropriately.
        // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        let nsError = error as NSError
        fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
    }
    return result
}()

let container: NSPersistentContainer

init(inMemory: Bool = false) {
    container = NSPersistentContainer(name: "test2CoreData")
    if inMemory {
        container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
    }
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

            /*
            Typical reasons for an error here include:
            * The parent directory does not exist, cannot be created, or disallows writing.
            * The persistent store is not accessible, due to permissions or data protection when the device is locked.
            * The device is out of space.
            * The store could not be migrated to the current model version.
            Check the error message to determine what the actual problem was.
            */
            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
    })
}

}

---- myapp.swift.

进口Swifui.

@主要的
struct myapp:app {
让persistenceController = persistenceController.shared

var body: some Scene {
    WindowGroup {
        ContentView()
            .environment(\.managedObjectContext, persistenceController.container.viewContext)
    }
}

}

- ContentView.

进口Swifui.
导入coredata.

struct contentView:查看{
@环境(.managedObjectContext)Private Var ViewContext

@FetchRequest(
    sortDescriptors: [NSSortDescriptor(keyPath: \Item.timestamp, ascending: true)],
    animation: .default)
private var items: FetchedResults<Item>

var body: some View {
    List {
        ForEach(items) { item in
            Text("Item at \(item.timestamp!, formatter: itemFormatter)")
        }
        .onDelete(perform: deleteItems)
    }
    .toolbar {
        #if os(iOS)
        EditButton()
        #endif

        Button(action: addItem) {
            Label("Add Item", systemImage: "plus")
        }
    }
}

private func addItem() {
    withAnimation {
        let newItem = Item(context: viewContext)
        newItem.timestamp = Date()

        do {
            try viewContext.save()
        } catch {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            let nsError = error as NSError
            fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
        }
    }
}

private func deleteItems(offsets: IndexSet) {
    withAnimation {
        offsets.map { items[$0] }.forEach(viewContext.delete)

        do {
            try viewContext.save()
        } catch {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            let nsError = error as NSError
            fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
        }
    }
}

}

私有允许itemformatter:dateformatter = {
让formatter = dateformatter()
formatter.datestyle = .short.
formatter.timestyle = .medium.medium.
返回格式化器
}()

struct contentview_previews:previewProvider {
静态VAR预览:有些视图{
ContentView()。环境(.managedObjectContext,persistencecontroller.preview.container.viewContext)
}
}

@cegrnd. 非常感谢您的问题!

这绝对是一个很好的建议。我们总是尽量确保我们在发布一本书时尽可能彻底,这绝对是包括在内的重要事项。随着SWIFTUI技术仍在发展,最终我们将能够提供更好的例子,这是彻底的,全面地为您提供最佳学习体验。

请保持调整,让您的眼睛保持打开以供未来的更新!

这一主题在166天后自动关闭。不再允许新的回复。