我有2個實體:Series和Season。一個系列可以有多個季節,所以我將關係類型設置爲「to many」。 season_counter是一個Int數組,包含劇集的數量。Swift - 如何將條目保存到循環中的核心數據中
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 _ {
}
}
在調試時我注意到,那season_counter存儲了正確的值。當我顯示結果,我只有上賽季存儲(例如13個集,seasons.count爲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 {
}
任何提示,以解決這個問題?
我得到了你的觀點。我有這樣的一個子類: 進口基金會 進口CoreData 類季節:NSManagedObject { } 的NSManaged價值觀在這裏:(帶@) 進口基金會 進口CoreData 擴展賽季{ NSManaged var id:NSNumber? NSManaged var value:NSNumber? NSManaged var集:NSNumber? NSManaged var series:Series? } 我現在該怎麼辦? – IceCoala