SwiftUI Preview canvas and Core Data

前端 未结 6 1771
孤独总比滥情好
孤独总比滥情好 2020-12-15 18:59

Preview canvas is is crashing but in simulator everything working fine. I assuming it related to @ObservedObject and @Fetchrequest...

tried solution for here Preview

6条回答
  •  情话喂你
    2020-12-15 19:29

    So, if you put some code in an onAppear handler in the preview, it will run on boot. It even live updates as you type!

    struct TemplateEditor_Previews: PreviewProvider {
      static var previews: some View {
        TemplateEditor().environment(\.managedObjectContext, AppDelegate.viewContext).onAppear {
          let entity = GlobalPlaceholders(context: AppDelegate.viewContext)
          entity.name = "abc123"
    
          // Or create more, if you need more example data
    
          try! AppDelegate.viewContext.save()
        }
      }
    }
    

    Note that I've wrapped up my viewContext in a static method on AppDelegate to make access a tiny bit less verbose and easier to remember:

    @UIApplicationMain
    class AppDelegate: UIResponder, UIApplicationDelegate {
      static var persistentContainer: NSPersistentContainer {
        return (UIApplication.shared.delegate as! AppDelegate).persistentContainer
      }
    
      static var viewContext: NSManagedObjectContext {
        return persistentContainer.viewContext
      }
    

提交回复
热议问题