B
B
Behtold_A2017-07-13 10:29:04
Swift
Behtold_A, 2017-07-13 10:29:04

How to get a list of available fields of the Core data entity?

There is a task to parse the data coming from the server and write them to the entity. The data comes in JSON format, is safely parsed into dictonary and even saved using the entity.setValuesForKeys(dictonary) method. However, there is a small problem. The fact is that the server in the output sometimes adds additional fields that are not in the entity. Why the application crashes...
For example, there is a class:

public class User {
       @NSManaged public var id: Int64
       @NSManaged public var name: String
}

JSON arrives, which is converted to dictonary : [String:Any]
{"id":1,"name":"Andrew"}
Everything is written to the instance safely, but it is worth adding an additional field:
{"id":1,"name" :"Andrew","temp":"Hop-hey"}, The compiler gives a message that the "temp" field does not exist in the User class. Is it possible to somehow get a list of the names of all available fields in the entity in order to further compare them with data from JSON and discard the excess.
Options for adding missing fields or variables to the object are not considered. SWIFT 3 is used.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Gorb, 2017-07-13
@Behtold_A

entity description
Pay attention to the properties:
Code 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)
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question