swiftUI核心数据@FetchRequest单个对象

问题描述

如何使用let attributedText = NSAttributedString(string: "Hello,playground",attributes: [ .foregroundColor: UIColor.red,.backgroundColor: UIColor.green,.ligature: 1,.strikethroughStyle: 1,]) let foundColor = attributedText.attribute(NSAttributedString.Key.foregroundColor,at: 0,effectiveRange: nil) // convert this to hex. //let cols = UIColor(cgColor: foundColor as! CGColor) // extendedSRGB.cgColor //foundColor.flatmap{Int($0)} // print(cols.extendedSRGB2sRGB) print(foundColor) // Optional(UIExtendedSRGBColorSpace 1 0 0 1) 来检索单个对象而不是@FetchRequest?我只需要一个对象。是否有另一种方法可以执行查询并根据唯一的属性值(例如ID)获得单个对象?

FetchedResults<Card>

解决方法

[继续我的评论] ...假设我们有Person实体并以某种方式存储/获取了某个对象的ID,这是一个可能的视图演示,该视图按ID获取该对象并对其进行处理>

注意:NSManagedObject符合ObservableObject

struct DemoPersonView: View {
    @ObservedObject var person: Person

    init(id objectID: NSManagedObjectID,in context: NSManagedObjectContext) {
        if let person = try? context.existingObject(with: objectID) as? Person {
            self.person = person
        } else {
            // if there is no object with that id,create new one
            self.person = Person(context: context)
            try? context.save()
        }
    }
    
    var body: some View {
      VStack {
        Text("User: \(person.name ?? "<Unknown>")")

        // ... other possible code to manage/edit person
      }
    }
}

通过Xcode 12 / iOS 14测试