NSOrderedSet和SwiftUI ForEach [英] NSOrderedSet and SwiftUI ForEach
本文介绍了NSOrderedSet和SwiftUI ForEach的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用CoreData和SwiftUI,并且有两个实体;狗和步行.狗之间是一对多的关系
I am trying to work with CoreData and SwiftUI and have two entities; Dog and Walk. It is a one-to-many relationship between Dog
public class Dog: NSManagedObject, Identifiable {
@NSManaged public var name: String?
@NSManaged public var walks: NSOrderedSet?
}
和步行
public class Walk: NSManagedObject, Identifiable {
@NSManaged public var date: Date?
@NSManaged public var dog: Dog?
}
我遇到的问题是在列表中显示所选狗的所有行走情况.以下WalksView将显示所有当前的步行
The problem I am having is displaying all of the walks for a selected dog in a List. The following WalksView will display all current walks
struct WalksView: View {
@ObservedObject var dogWalksVM:DogWalkVM
var selectedIndex:Int
var body: some View {
let currentDog = dogWalksVM.dogs[selectedIndex]
return List {
if currentDog.walks == nil {
EmptyView()
} else {
ForEach(0..<currentDog.walks!.count) { index in
Text("Date \(self.walkDate(currentDog.walks![index] as! Walk))")
}
}
}
.navigationBarTitle(Text("Walks for \(dogWalksVM.dogs[selectedIndex].name ?? "")"), displayMode: .inline)
.navigationBarItems(trailing: Button(action: {
self.addWalk(for: currentDog)
}, label: {
Image(systemName: "plus")
}))
}
func walkDate(_ walk:Walk) -> String{
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
guard let walkDate = walk.date as Date? else { return ""}
return dateFormatter.string(from: walkDate)
}
func addWalk(for currentDog:Dog) {
self.dogWalksVM.addWalk(for: currentDog)
}
}
但是当我添加一个新应用时,该应用程序崩溃并显示以下错误:
but when I add a new one, the app crashes with the following error:
ForEach<Range<Int>, Int, Text> count (1) != its initial count (0).
`ForEach(_:content:)` should only be used for *constant* data.
Instead conform data to `Identifiable` or use `ForEach(_:id:content:)` and provide an explicit `id`!
如果我尝试在这样的步行道上进行ForEach:
If I try to do a ForEach on the walks like this:
ForEach(Array(currentDog.walks!),id: \.self) { walk in
Text("Date \(self.walkDate(walk))")
}
我被告知
Protocol type 'NSOrderedSet.Element' (aka 'Any') cannot conform to 'Hashable' because only concrete types can conform to protocols
推荐答案
以下内容应为您提供帮助
The following should help you
ForEach(Array(currentDog.walks!.set),id: \.self) { walk in
Text("Date \(self.walkDate(walk))")
}
这篇关于NSOrderedSet和SwiftUI ForEach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文