johann
johann

Reputation: 1135

Swift 2: Save coredata with one-to-many conditions

I want to bind my 2 models with swift 2:

one-to-many swift2

The "BodyPart" table :

enter image description here

The "Muscle" table :

enter image description here

I just want to save a "BodyPart" with its "Muscles":

  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 is saved in the CodeData, however the Muscles list is empty. Thank you

Upvotes: 1

Views: 135

Answers (1)

vadian
vadian

Reputation: 285079

The default collection type of Core Data is NSSet rather than NSArray

You can get allObjects from the set which returns an array

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

But since you know from the Core Data model that muscles exists, I'd recommend to declare the attribute as non-optional and omit the optional binding.

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

Upvotes: 4

Related Questions