我的核心数据模型中有两个实体:CardCollection(类名CardCollectionMO)和Card(CardMO)。一个CardCollection可以有很多卡。这是我的代码,用于使用一组新卡保存CardCollection,这似乎工作正常。
func saveCardInfo() {
let currentDate = createDate()
let collectionNumber = arc4random_uniform(1000000)
let cardcollection = CardCollectionMO.insertNewCollection(collectionNumber: Int64(collectionNumber), collectionTitle: collectionTitle.text!, collectionDescription: collectionDescription.text!, numberOfCards: Int16(cards.count), dateCreated: String(currentDate))
var newCard = Set<CardMO>()
for card in cards {
if let addedCard = CardMO.insertNewCard(questionText: card.questionText, answerText: card.answerText, cardNum: Int16(card.cardNum), questionImage: UIImageJPEGRepresentation(card.questionImage, 1)! as NSData) {
addedCard.cardcollection = cardcollection
newCard.insert(addedCard)
}
}
cardcollection?.addToCards(newCard as NSSet)
}
但是,取回数据时会发生奇怪的事情。这是代码。
func fetchData() {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let managedObjectContext = appDelegate.persistentContainer.viewContext
let request = NSFetchRequest<CardCollectionMO>(entityName: "CardCollection")
do {
let results = try managedObjectContext.fetch(request)
if results.count > 0 {
for result in results {
if let collectionTitle = result.collectionTitle {
print(collectionTitle)
}
if let listOfCards = result.cards?.allObjects as? [CardMO] {
for card in listOfCards {
if let questionText = card.questionText {
print(questionText)
}
}
上面的代码在应用程序运行时运行良好,但是如果我停止并重新启动应用程序,则将删除每个集合中的最后一张卡片。我已经完成了listOfCards.count,并且它不存在。但是,如果我只是从Card实体获取所有卡,它们就在那里。关于我做错了什么以及为什么不提取收藏集中的最后一张卡片的任何想法?