Core Data in Swift: Only saving last object in a for loop

You dont need to create a request to save new objects to Core Data. What you did wrong was create a single managed object, inserted it and then changeded it through the loop instead of creating a new object for each song.

This should work:

func fetchiPodSongsOnSignup() {

    var appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

    var context: NSManagedObjectContext = appDel.managedObjectContext!


    let query = MPMediaQuery.songsQuery()

    let result = query.collections as! [MPMediaItemCollection]

    for song in result {

        for song in song.items as! [MPMediaItem] {

            var newSong = NSEntityDescription.insertNewObjectForEntityForName("IPodSongs", inManagedObjectContext: context) as NSManagedObject

            newSong.setValue("\(song.valueForProperty(MPMediaItemPropertyTitle))", forKey: "title")

            println(newSong)


        }
    }
    if context.save(&errorPointer == false {
        printlin("Error received while saving")
    }

}

Also put if context.save(&errorPointer == false {printlin("Error received while saving")} at the very end.

Leave a Comment