UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: CoreData keeps adding multiple values

Forums > SwiftUI

When i use the below code to loop over an array of objects , i get each value being added multiple times, how can i over come this , i get the proper data from the API call though and is saved properly to the array , but while trying to save to core data and looping over ojects , the values are repeated ...kindly suggest

struct MovieData: Codable {
    var poster_path: String?
    var title: String
    var release_date: String
    var id: Int
    var overview: String
}

struct MovieList: Codable {
    var page: Int
    let results: [MovieData]
}
 Button("Save") {
                    Task {
                        for result in viewModel.results {

                            let moviesFile = MovieContent(context: managedObjectContext)
                            moviesFile.title = result.title
                            moviesFile.poster_path = result.poster_path
                            moviesFile.release_date = result.release_date
                            moviesFile.id = Int32(result.id)
                            moviesFile.genre = "popular"
                            moviesFile.overview = result.overview
                            try managedObjectContext.save()

                        }

                    }

1      

Move let moviesFile = MovieContent(context: managedObjectContext) outside the for loop because you create it ever time it loop over

1      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.