简体   繁体   中英

Swift - How to save entries to core data in a loop

I have 2 entities: Series and Season. A Series can have multiple seasons, so I set the relationship type to "to many". season_counter is an Int Array, containing the amount of episodes.

let newSeries = NSEntityDescription.insertNewObjectForEntityForName("Series", inManagedObjectContext: self.context!) as! Series

for var i = 0; i < season_counter.count; ++i{
         let newSeason = NSEntityDescription.insertNewObjectForEntityForName("Season", inManagedObjectContext: self.context!) as! Season
         newSeason.value = i+1
         newSeason.episodes = season_counter[i]
         newSeries.setValue(NSSet(object: newSeason), forKey: "seasons")

     do {
         try context?.save()
    } catch _ {
    }
}

While debugging I noticed, that season_counter stores the correct values. When I display the results, I have only the last season stored (for example 13 episodes, seasons.count is 1):

do {
    let fetchRequest = NSFetchRequest(entityName: "Season")
    fetchRequest.predicate = NSPredicate(format: "series = %@", series)
    try seasons = context?.executeFetchRequest(fetchRequest) as! [Season]

    print(seasons.count)
    print(seasons[0].episodes)
} catch {
}

Any tips to solve this?

In each pass through your loop, you're throwing away the previous value of seasons and replacing it with a set that contains only one season (the newly created newSeason ):

     newSeries.setValue(NSSet(object: newSeason), forKey: "seasons")

Instead of doing that, build up a set of all of the newSeason instances, and then call setValue:forKey: once, with that set.

Your life will be easier, by the way, if you create subclasses of NSManagedObject and get out of the "value for key" business.

newSeries.setValue(NSSet(object: newSeason), forKey: "seasons")

With this line you always create a new set of seasons containing exaclty one Season object - newSeason .

Try to do that:

var prevSeasons = newSeries.valueForKey("seasons")  
prevSeasons.insert(newSeason)
newSeries.setValue(prevSeasons, forKey: "seasons")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM