Swift: Reflecting properties of subclass of NSMana

2019-04-09 00:44发布

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
}

How can reflection mechanisms used on NSManagedObjects.

1条回答
贪生不怕死
2楼-- · 2019-04-09 01:24

The accessor methods for Core Data properties are synthesized dynamically at runtime.

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.

A simple example:

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)
}
查看更多
登录 后发表回答