Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Reflecting properties of subclass of 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
}

How can reflection mechanisms used on NSManagedObjects.

like image 900
Guardian667 Avatar asked Dec 22 '15 08:12

Guardian667


People also ask

How do I create a subclass in NSManagedObject?

From the Xcode menu bar, choose Editor > Create NSManagedObject Subclass. Select your data model, then the appropriate entity, and choose where to save the files. Xcode places both a class and a properties file into your project.

What is NSManagedObject in ios?

In some respects, an NSManagedObject acts like a dictionary—it's a generic container object that provides efficient storage for the properties defined by its associated NSEntityDescription instance.

What is NSManagedObject context?

An object space to manipulate and track changes to managed objects.

What is Core Data in swift IOS?

Overview. Use Core Data to save your application's permanent data for offline use, to cache temporary data, and to add undo functionality to your app on a single device. To sync data across multiple devices in a single iCloud account, Core Data automatically mirrors your schema to a CloudKit container.


1 Answers

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)
}
like image 106
Martin R Avatar answered Sep 21 '22 03:09

Martin R