1structChildView_Previews:PreviewProvider{2staticvar previews: some View{3ChildView().environment(\.managedObjectContext,PersistenceController.preview.container.viewContext)4}5}
1// Persistence2importCoreData34structPersistenceController{5staticlet shared =PersistenceController()67staticvar preview:PersistenceController={8let result =PersistenceController(inMemory:true)9let viewContext = result.container.viewContext
10for i in0..<10{11let newItem =Item(context: viewContext)12 newItem.index =Int16(i)13 newItem.name ="name\(i)"14}15do{16try viewContext.save()17}catch{18// Replace this implementation with code to handle the error appropriately.19// 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.20let nsError = error asNSError21fatalError("Unresolved error \(nsError), \(nsError.userInfo)")22}23return result
24}()2526let container:NSPersistentContainer2728init(inMemory:Bool=false){29 container =NSPersistentContainer(name:"PreviewProduct")30if inMemory {31 container.persistentStoreDescriptions.first!.url =URL(fileURLWithPath:"/dev/null")32}33 container.loadPersistentStores(completionHandler:{(storeDescription, error)in34iflet error = error asNSError?{35// Replace this implementation with code to handle the error appropriately.36// 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.3738/*
39 Typical reasons for an error here include:
40 * The parent directory does not exist, cannot be created, or disallows writing.
41 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
42 * The device is out of space.
43 * The store could not be migrated to the current model version.
44 Check the error message to determine what the actual problem was.
45 */46fatalError("Unresolved error \(error), \(error.userInfo)")47}48})49 container.viewContext.automaticallyMergesChangesFromParent =true50}51}
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/09/18 02:27