1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

FetchRequestするViewにPreview用のデータを渡してPreviewする

Posted at

CoreData使用プロジェクトを新規作成した際のPersistenceControllerのままでいけるが、自身が忘れそうなので。

大事な点

  • PersistenceControllerの静的変数previewにPersistenceController自身をセットする。そのcontainerプロパティのviewContextにpreview用データがsaveされる。
  • environmentでmanagedObjectContextにpreview用コンテキストを設定する。
View.swift
import SwiftUI
import CoreData

struct PeopleView: View {
    @FetchRequest(entity: Person.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Person.name, ascending: true)],animation: .default)
    var people: FetchedResults<Person>
    
    var body: some View {
                List(people){ person in
                    PersonRow(person)
                }
    }
}

struct PeopleView_Previews: PreviewProvider {
    static var previews: some View {
        PeopleView()
            .environment(\.managedObjectContext,
                          PersistenceController.preview.container.viewContext)//ここでpreview用viewContextをセット
    }
}

PersistenceController.swift
import CoreData

struct PersistenceController {
    static let shared = PersistenceController()
    let container: NSPersistentContainer
    
//preview用viewContext置き場、viewContextにはpreview用データが入っている
    static var preview: PersistenceController = {
        let result = PersistenceController(inMemory: true)
        let viewContext = result.container.viewContext
        for i in 0..<10 {
            let newItem = Person(context: viewContext)
            newItem.name = "\(i)太郎"
            newItem.occupation = "エンジニア"
        }
        
        do {
            try viewContext.save()
        } catch {
            let nsError = error as NSError
            fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
        }
        return result
    }()
    
    init(inMemory: Bool = false) {...}//CoreData使用プロジェクトを作成した際に作られる
}


1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?