How to convert NSManagedObject to NSDictionary

橙三吉。 提交于 2019-11-30 09:22:48

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 needs to 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 NSManagedObjects, 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}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!