Rohitax Rajguru
Rohitax Rajguru

Reputation: 923

How to check for core data attribute type at runtime?

I want to check the type of attributes datatype at runtime in Swift. Like while inserting I want to check if the particular attribute in an entity accepts value of date type or string type. How this can be achieved in Swift.

Upvotes: 2

Views: 1699

Answers (3)

Jon Rose
Jon Rose

Reputation: 8563

In general, you should know what your model is before you write your code. So introspecting on a readonly model seems a little silly. I can't think of any reason why you would ever want to do this, but I'm sure you have a good reason that you aren't sharing.

You can look at a managedObject entity class method (on your subclass) which is a NSEntityDescription. Or you can get all the entity descriptions directly from your model object (context.persistentStoreCoordinator.managedObjectModel.entites) or if you know the entity's name you can use context.persistentStoreCoordinator. managedObjectModel.entitiesByName["EntityName"]. The entity description will tell you all about the entities properties. You can look through each of the attributes and get a NSAttributeDescription which will tell you the type for that attribute.

Upvotes: 0

Sandeep
Sandeep

Reputation: 21144

You can always use entity's attribute description which is of type NSAttributeDescription to find out the correct type of the property that is defined in model.

If say you have a subclass of NSManagedObject, Person. Then, you could use example from following code to check the type before inserting,

@objc(Person)
class Person: NSManagedObject {
  @NSManaged
  var name: String

  @NSManaged
  var age: NSNumber

  @NSManaged
  var dateOfBirth: Date
}

let person = NSEntityDescription.insertNewObject(forEntityName: "Person", into: context) as! Person

if let attribute = person.entity.attributesByName["name"],
                      attribute.attributeType == .stringAttributeType {

  // use your code here for custom logic
  print("name is string")
}

if let attribute = person.entity.attributesByName["age"], 
                      attribute.attributeType == .dateAttributeType {

  // use your code here for custom logic

  print("age is date")
}

Upvotes: 4

Lawliet
Lawliet

Reputation: 3499

It's type(of:).E.g.,

let test: Int = 0
if type(of: test) == Int.self {
    print("found")
}

Upvotes: 0

Related Questions