Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios swift中循环ManagedObject插入的语法_Ios_Swift_Core Data - Fatal编程技术网

Ios swift中循环ManagedObject插入的语法

Ios swift中循环ManagedObject插入的语法,ios,swift,core-data,Ios,Swift,Core Data,在使用Swift勘探核心数据的过程中,作为测试,我有以下功能: func insertObject (entityName:String) { var newItem = NSEntityDescription.insertNewObjectForEntityForName(entityName, inManagedObjectContext:managedObjectContext!) as! EventList let now = NSDate() newItem.d

在使用Swift勘探核心数据的过程中,作为测试,我有以下功能:

func insertObject (entityName:String) {
    var newItem = NSEntityDescription.insertNewObjectForEntityForName(entityName, inManagedObjectContext:managedObjectContext!) as! EventList
    let now = NSDate()
    newItem.date = now
    newItem.eventDescription = “Whatever Anniversary"
}
这似乎有效,但为了使我的函数更有用,我想向它传递一个描述我要插入的对象的词汇表。 如下所示:

func insertObject (entityName:String,dico:NSDictionary) {
    var newItem = NSEntityDescription.insertNewObjectForEntityForName(entityName, inManagedObjectContext:managedObjectContext!) as! EventList
    for (key, value) in dico {
        println("\(key) : \(value)")
        newItem.key = value
    }
}
问题来了,这条线错了:

    newItem.key = value
正确的语法是什么

这行显示循环部分工作正常:

    println("\(key) : \(value)")

您可以对托管对象使用键值编码:

func insertObject (entityName:String, dico: [String : NSObject]) {
    let newItem = NSEntityDescription.insertNewObjectForEntityForName(entityName, inManagedObjectContext:managedObjectContext!) as! EventList
    for (key, value) in dico {
        newItem.setValue(value, forKey: key)
    }
}
可以缩短为

func insertObject (entityName:String, dico: [String : NSObject]) {
    let newItem = NSEntityDescription.insertNewObjectForEntityForName(entityName, inManagedObjectContext:managedObjectContext!) as! EventList
    newItem.setValuesForKeysWithDictionary(dico)
}
这种通用方法的问题在于,它会在某个时间崩溃 运行时,如果字典包含非属性的键
或者如果数据类型不匹配。

谢谢,它可以工作。除了“newItem.setValue(value,forKey:key)”之外,我必须使用“newItem.setValue(value,forKey:key as!String)”来避免编译错误。稍后我将尝试缩短的语法。@michell:注意,我将“dico”参数的类型更改为
[String:NSObject]
,这样就不必强制转换键了。