Swift:反映NSManagedObject子类的属性 [英] Swift: Reflecting properties of subclass of NSManagedObject
本文介绍了Swift:反映NSManagedObject子类的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用镜像访问NSManagedObject子类的内部结构时,将忽略所有托管变量。
When accessing the inner structure of a subclass of NSManagedObject using a Mirror, all managed variables are ignored.
public class Foo: NSManagedObject {
@NSManaged var bar: String?
}
var f: Foo = ...
// ... creating a Foo in a valid context ...
let mirror = Mirror(reflecting: f)
for c in mirror.children { // children count == 0
print("\(c.label!):\(c.value)") // never executed
}
如何在NSManagedObjects上使用反射机制。
How can reflection mechanisms used on NSManagedObjects.
推荐答案
Core Data属性的访问器方法在运行时动态地合成
。
The accessor methods for Core Data properties are synthesized dynamically at runtime.
您可以使用
的 NSManagedObject
的实体
属性来枚举Core Data实体的属性。是 NSEntityDescription
并具有 attributesByName
属性。
You can enumerate the attributes of a Core Data entity using
the entity
property of NSManagedObject
which is a NSEntityDescription
and has a attributesByName
property.
一个简单的示例:
for (name, attr) in newManagedObject.entity.attributesByName {
let attrType = attr.attributeType // NSAttributeType enumeration for the property type
let attrClass = attr.attributeValueClassName ?? "unknown"
print(name, "=", newManagedObject.valueForKey(name), "type =", attrClass)
}
这篇关于Swift:反映NSManagedObject子类的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文