当前位置: 动力学知识库 > 问答 > 编程问答 >

ios - Is it possible to enumerate NSDictionary keys to set datamodel member values?

问题描述:

I have a dictionary contains (for example)

"Mark":"Name","Green":"Lastname"

and I have a datamodel with following:

@interface Person : NSManagedObject

@property (nonatomic, retain) NSString * Name;

@property (nonatomic, retain) NSString * Lastname;

Can I enumerate dictionary allkeys to set datamodel member values?

something like this:

let newPerson = CoreDataHelper.insertManagedObject(NSStringFromClass(Person), managedObjectContext: self.moc) as! Person

for key in self.newPersonDict!.allKeys {

newPerson.key = self.newPersonDict!.objectForKey(key)

}

Thanks,

Max

网友答案:

Try something like this:

let newPerson = CoreDataHelper.insertManagedObject(NSStringFromClass(Person), managedObjectContext: self.moc) as! Person

for key in self.newPersonDict!.allKeys {
    newPerson.setValue(self.newPersonDict!.valueForKey(key), forKeyPath: key)   
}
网友答案:

You can use func setValuesForKeysWithDictionary(_ keyedValues: [NSObject : AnyObject])

网友答案:

As said in one of the comments, you can achieve this with reflection. There are probably better ways to do this, but here is an example on how you can do it

class YourClass : NSObject {

    func getKeys() -> Array<String> {
        let mirror = reflect(self)
        var keys = [String]()
        for i in 0..<mirror.count {
            let (name,type) = mirror[i]
            keys.append(name)
        }
        return keys
    }

    func getObjectForKey(key: String) -> AnyObject? {
        return self.valueForKey(key)
    }

}

You would still have to cast AnyObject? to your specific type, and be careful, valueForKey can result in exceptions when it's called with an unknown key.

分享给朋友:
您可能感兴趣的文章:
随机阅读: