How to convert NSManagedObject to NSDictionary

1110 picture 1110 · Apr 16, 2015 · Viewed 8.1k times · Source

I am trying to convert NSManagedObject to NSDictionary this is what I tried:

var keys:NSArray = order?.entity.attributesByName.keys
var dict:NSDictionary = order?.dictionaryWithValuesForKeys(keys)

But I get error:

 LazyForwardCollection<MapCollectionView<Dictionary<NSObject,
 AnyObject>, NSObject>>? is not convertible to NSArray.

What am I doing wrong here?

Answer

Martin R picture Martin R · Apr 16, 2015

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
}