gpt4 book ai didi

ios - 如何使用 Swift 中的核心数据正确映射一对多关系?尝试期间出现 NSInvalidArgumentException 错误

转载 作者:行者123 更新时间:2023-11-28 13:01:46 26 4
gpt4 key购买 nike

这是我的医学对象类和扩展:

import Foundation
import CoreData

class Medicine: NSManagedObject {

@NSManaged var alarms: NSSet

}

-

import Foundation
import CoreData

extension Medicine {

@NSManaged var name: String?
@NSManaged var dosage: String?
@NSManaged var type: String?
@NSManaged var image: NSData?

func addAlarmObject(value:Alarm) {
let items = self.mutableSetValueForKey("alarms")
items.addObject(value)
}

func removeDeleteObject(value:Alarm) {
let items = self.mutableSetValueForKey("alarms")
items.removeObject(value)
}

}

我的报警对象:

import Foundation
import CoreData

extension Alarm {

@NSManaged var time: String?
@NSManaged var weekdays: String?
@NSManaged var isOwnedByMedicine: Medicine?

}

我的数据模型及其关系的屏幕截图:

enter image description here

最后,这是我要做的:

        let predicate = NSPredicate(format: "name == %@", currentMedicine)
let fetchRequest = NSFetchRequest(entityName: "Medicine")
fetchRequest.predicate = predicate
var fetchedCurrentMedicine:Medicine!
do {
let fetchedMedicines = try managedContext.executeFetchRequest(fetchRequest) as! [Medicine]
fetchedCurrentMedicine = fetchedMedicines.first
} catch {

}

//add all the alarms to the Medicine class
for alarmString in alarmList{
let entity = NSEntityDescription.entityForName("Alarm", inManagedObjectContext: managedContext)
let alarm = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext) as! Alarm
alarm.setValue("test", forKey: "weekdays")
alarm.setValue(String(alarmString), forKey: "time")
fetchedCurrentMedicine.addAlarmObject(alarm)
}
do {
try managedContext.save()
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
}

一直失败

fetchedCurrentMedicine.addAlarmObject(alarm)

我得到了错误:

“‘NSInvalidArgumentException’,原因:实体‘Medicine’的‘NSManagedObjects’不支持属性‘alarms’的-mutableSetValueForKey:”

知道我可能在哪里搞砸了或弄错了数据模型的模式吗?非常感谢。

最佳答案

在您的数据模型屏幕上,alarms Medicine 模型的关系是对一个。也许Alarm模型的medicines关系是to-many
无论如何尝试在数据模型检查器中为 alarms 设置to-many 关系类型。

关于ios - 如何使用 Swift 中的核心数据正确映射一对多关系?尝试期间出现 NSInvalidArgumentException 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33686579/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com