Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.3k views
in Technique[技术] by (71.8m points)

swift - PreviewProvider and ObservedObject properties

how can I set a property to my CoreData Object which has the type CDObject, it has a property called name: String

My issue is now that I do not know how to set the name property in the PreviewProvider

Here is the code:

struct MainView: View {
    @ObservedObject var obj: CDObject
    
    var body: some View {
        Text("Hello, World!")
    }
}

struct MainView_Previews: PreviewProvider {
    static var previews: some View {
        MainView(obj: CDObject())
    }
}

I would like to do something like, before passing it to the View:

let itm = CDObject()
itm.name = "Hello"
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you are using the standard PersistenceController that comes with Xcode when you start a new project with CoreData just add the below method so Xcode returns the .preview container when you are running in preview.

    public static func previewAware() -> PersistenceController{
        //Identifies if XCode is running for previews
        if ProcessInfo.processInfo.environment["XCODE_RUNNING_FOR_PREVIEWS"] == "1"{
            return PersistenceController.preview
        }else{
            return PersistenceController.shared
        }
    }

As for the rest you can use something like this.

import SwiftUI
import CoreData

struct SamplePreviewView: View {
    @ObservedObject var item: Item
    var body: some View {
        Text(item.timestamp?.description ?? "nil")
    }
}
struct SamplePreviewView_Previews: PreviewProvider {
    static let svc = CoreDataPersistenceService()
    static var previews: some View {
        SamplePreviewView(item: svc.addSample())
    }
}

class CoreDataPersistenceService: NSObject {

    var persistenceController: PersistenceController

    init(isTest: Bool = false) {
        if isTest{
            self.persistenceController = PersistenceController.preview
        }else{
            self.persistenceController = PersistenceController.previewAware()
        }
        super.init()
    }
    func addSample() -> Item {
        let object = createObject()
        object.timestamp = Date()
        return object
    }
    //MARK: CRUD methods
    func createObject() -> Item {
        let result = Item.init(context: persistenceController.container.viewContext)
        return result
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...