如何解决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测试
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。