简体   繁体   中英

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

您可以使用func setValuesForKeysWithDictionary(_ keyedValues:[NSObject:AnyObject])

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)   
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM