How to convert NSManagedObject to NSDictionary
The keys
property of a dictionary returns a LazyForwardCollection
which has to be converted to a real array.
Another problem is that order
is apparently an optional, so it needsto be unwrapped, e.g. with optional binding.
if let theOrder = order { let keys = Array(theOrder.entity.attributesByName.keys) let dict = theOrder.dictionaryWithValuesForKeys(keys)} else { // order is nil}
Instead of getting the objects out of the database as NSManagedObject
s, you could set the resultType
, on your NSFetchRequest
, to DictionaryResultType
to have Dictionaries returned when you execute the request.
However, you will not be able to edit values in these dictionaries and have the changes saved in your database. If you just need to read from your database, then that isn't a problem.
Not elegant but this should work...
var names = Array<String>()for attributeName in order?.entity.attributesByName.keys{ names.append(attributeName as! String)}
This is a problem of converting some kind of collection to another, which is never trivial even if internal types are same.
edit : little more swift spirit
var names = map(order?.entity.attributesByName.keys){return $0 as! String}