Swift 2:使用一对多条件保存coredata

时间:2015-10-29 08:13:27

标签: ios swift core-data swift2

我想用swift 2绑定我的2个模型:

one-to-many swift2

" BodyPart"表:

enter image description here

"肌肉"表:

enter image description here

我只想保存一个" BodyPart"与其#34;肌肉":

  if let managedObjectContext = self.managedObjectContext {

                do{

                    // create a bodyPart
                     let bodyPart = NSEntityDescription.insertNewObjectForEntityForName("BodyPart",inManagedObjectContext: managedObjectContext) as! BodyPart

                    // create a Muscle
                    let muscle = NSEntityDescription.insertNewObjectForEntityForName("Muscle",inManagedObjectContext: managedObjectContext) as! Muscle


                    //muscles attributes
                    muscle.name = "test"
                    muscle.image = "myimage.png"

                    // mobdypart attributes
                    bodyPart.name="mybody-part test"
                    bodyPart.muscles = [muscle]

                    //save
                    try managedObjectContext.save()


                    // get all muscles
                    let fetchRequest = NSFetchRequest(entityName: "BodyPart")

                    /* Get result array from ManagedObjectContext */
                    let fetchResults = try managedObjectContext.executeFetchRequest(fetchRequest)

                    // list body parts
                    if let results: Array = fetchResults {
                        for obj:AnyObject in results {

                            let name:String? = obj.valueForKey("name") as? String
                            print("name for the BodyPart: \(name) ")

                            // list muscles => always empty !!
                            if let muscles: Array<Muscle> = obj.valueForKey("muscles") as? Array<Muscle> {
                                for ob:Muscle in muscles {
                                    print("### name for the muscles: \(ob.name)")
                                }
                            }

                        }

                    } else {
                        print("Could not fetch")
                    }


                } catch let error as NSError  {
                    print(error)
                }
            }

BodyPart保存在CodeData中,但肌肉列表为空。 谢谢

1 个答案:

答案 0 :(得分:4)

核心数据的默认集合类型为NSSet,而不是NSArray

您可以从返回数组的集合中获取allObjects

if let muscles: Array<Muscle> = (obj.valueForKey("muscles") as! NSSet).allObjects as? Array<Muscle> { ...

但是,由于您从Core Data模型中知道muscles存在,我建议将该属性声明为非可选属性并省略可选绑定。

let muscles = obj.valueForKey("muscles") as! NSSet