Post not yet marked as solved
Post marked as unsolved with 0 replies, 588 views
I am trying to display a simple list of text based on an NSManagedObject subclass. In this class, I am not doing any fetch requests, I am simply passing in a list that was already fetched.
When trying to preview this view, the preview keeps crashing and I can't figure out why. It does not crash when this view is created as a subview in another preview.
Swift
import SwiftUI
struct TracksView: View {
var songs: [Song] = []
var body : some View {
List(songs.map{$0.title!}, id:
\.self){(song:String) in
Text(song)
}
}
}
struct TracksView_Previews: PreviewProvider {
static var context = PersistenceController.preview.container.viewContext
static var songs: [Song] = {
let req = NSFetchRequestNSFetchRequestResult(entityName: Song.className())
var s:[Song]?
do {
let data = try context.fetch(req)
if data.first! is Song{
s = data as? [Song]
}
} catch {
print(error.localizedDescription)
}
return s ?? []
}()
static let env = Global()
static var previews: some View {
TracksView(songs: songs)
.environment(\.managedObjectContext, context)
.environmentObject(env)
}
}