Author Topic: How to get a list of an object's properties  (Read 3451 times)

kjmcneish

  • Administrator
  • *****
  • Posts: 719
    • View Profile
How to get a list of an object's properties
« on: November 24, 2014, 10:01:53 AM »
If you want to get the list of properties of a Core Data entity, you can do the following (I'm explicitly declaring the variables' types to make the code more readable):

Code: [Select]
var entity = self.createEntity()
       
// 1. Get an entity description
var entityDescription: NSEntityDescription? = NSEntityDescription.entityForName(self.entityClassName, inManagedObjectContext: self.managedObjectContext!)
       
// 2. Create a dictionary containing the entity's attributes
var attributesDictionary = entityDescription?.attributesByName as! [String: NSAttributeDescription]
       
// 3. Get the description of a specified property
var propertyDescription: NSAttributeDescription = attributesDictionary["firstName"]!
       
// 4. Get the entity object's property type
var propertyType: NSAttributeType = propertyDescription.attributeType
       
// 5.  Get the property value
var propValue : AnyObject! = entity.valueForKey("firstName")
       
// 6. Set the property value
entity.setValue("Kevin", forKey: "firstName")

If you need to get the same information for an object that is NOT a Core Data entity, you can do the following:
Code: [Select]
var entity = self.createEntity()
// Get a list of the entity's properties
var propertiesCount : CUnsignedInt = 0
let propertyList : UnsafeMutablePointer<objc_property_t> = class_copyPropertyList(T.self, &propertiesCount)
       
// Iterate through the list of properties
for var i = 0; i < Int(propertiesCount); i++ {
           
     // Get the property structure        var property: objc_property_t = propertyList[i]
           
     // Get the property name
     var propName: NSString? = NSString(CString: property_getName(property), encoding: NSUTF8StringEncoding)
           
     // Get the property type
     var propType: UnsafePointer<Int8> = property_getAttributes(property)
           
     // Get the property value
     var propValue : AnyObject! = entity.valueForKey(propName! as String);
           
     // Set the property value
     entity.setValue("Apple, Inc", forKey: propName! as String)
 }
       
free(propertyList)

All the best!
Kevin McNeish
Author of "Learn to Code in Swift": https://itunes.apple.com/us/book/learn-to-code-in-swift/id942956811?mt=11
« Last Edit: August 16, 2015, 03:58:21 PM by kjmcneish »