• 赚钱入口【需求资源】限时招募流量主、渠道主,站长合作;【合作模式】CPS长期分成,一次推广永久有收益。主动打款,不扣量;

Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason: ‘-[MyChems.DrugObject copyWithZone:]: unrecognized selector sent to instance ‘

iOS cps12345 3个月前 (09-10) 67次浏览 0个评论

我正在尝试使用来自Core Data的数据构建S​​wiftUI视图。其中一个实体与另一个实体具有一对多关系。我有一个基本的主详细信息类型,并带有一个到第二个视图的NavigationLink,该视图应等效于一个详细视图。实际上,我可以列出第二个实体的所有详细信息,但相关对象集除外。

相关实体:

public class Regimen : NSManagedObject, Identifiable {
    @NSManaged public var id: UUID
    @NSManaged public var name: String?
    //...more

    @NSManaged public var drugObjects: Set<DrugObject>
}

public class DrugObject : NSManagedObject, Identifiable {
    @NSManaged public var id: UUID
    @NSManaged public var name: String?
    //...more

    @NSManaged public var regimen: Regimen
}

主列表:

struct RegimenListView: View {
    @Environment(\.managedObjectContext) var managedObjectContext
    @FetchRequest(fetchRequest: Regimen.getAllRegimens()) var myRegimens
    var body: some View {
        NavigationView {
            List {
                ForEach(myRegimens, id: \.self) { mr in
                    NavigationLink(destination: RegimenDetailView(regimen: mr)) {
                        Text(mr.name ?? "no regimen name")
                    }
                }
            }.navigationBarTitle("Regimens")
        }
    }
}

详细清单:

struct RegimenDetailView: View {
    var regimen: Regimen
    var body: some View {
        //let da: [DrugObject] = Array(regimen.drugObjects)
        return NavigationView {
            VStack {
                Text(regimen.name ?? "no regimen name")
                List {
                    ForEach(regimen.drugObjects, id: \.self) { x in
                        Text(x.name ?? "no drugObject name")
                    }
                }
            }
        }
    }
}

如果我尝试如上所述构建,则会在ForEach行上收到错误消息

Generic struct ‘ForEach’ requires that ‘Set’ conform to ‘RandomAccessCollection’

如果我首先尝试转换为数组,它会因以下错误而崩溃

Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason: ‘-[MyChems.DrugObject copyWithZone:]: unrecognized selector sent to instance ‘

解决

尝试添加

extension DragObject: NSCopying {
    func copy(with zone: NSZone? = nil) -> Any {
        return self
    }
}

和使用

List {
    ForEach(Array(regimen.drugObjects), id: \.self) { x in
        Text(x.name ?? "no drugObject name")
    }
}
喜欢 (0)
发表我的评论
取消评论
表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址