我试图学习如何在核心数据中使用这种奇特的新关系模式来模拟字符串数组。我有一个报警实体和一个通知实体。报警是NotificationUuid的父实体,因为报警可以有许多NotificationUuid,而NotificationUuid只能有一个父报警。我在.xcdatamodeld文件中设置了所有这些。
我的问题是:当我像这样获取父报警对象时:
private func loadAlarms() {
os_log("loadAlarms() called", log: OSLog.default, type: .debug)
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}
let managedContext = appDelegate.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<AlarmMO>(entityName: "Alarm")
do {
if self.alarms.count == 0 {
self.alarms = try managedContext.fetch(fetchRequest)
os_log("Loading %d alarms", log: OSLog.default, type: .debug, self.alarms.count)
} else {
os_log("Didn't need to load alarms", log: OSLog.default, type: .debug)
}
} catch let error as NSError {
print("Could not fetch alarms. \(error), \(error.userInfo)")
}
}
是否免费获取AlarmMO(报警管理对象)对象的子对象NotificationUuid对象?或者我现在也必须为它们设置一个获取请求吗?这种奇特的亲子关系是如何工作的,我如何从这些实体中设置/加载内容?
谢谢
以下是我对AlarmMO的定义:
import CoreData
@objc(AlarmMO)
public class AlarmMO: NSManagedObject {
@NSManaged public var alarmNumber: Int64
@NSManaged public var alarmTime: NSDate?
@NSManaged public var endTimeInterval: Double
@NSManaged public var recurrence: Int64
@NSManaged public var startTimeInterval: Double
@NSManaged public var notificationUuidChildren: NSSet?
}
// MARK: Generated accessors for notificationUuidChildren
extension AlarmMO {
@objc(addNotificationUuidChildrenObject:)
@NSManaged public func addToNotificationUuidChildren(_ value: NotificationUuidMO)
@objc(removeNotificationUuidChildrenObject:)
@NSManaged public func removeFromNotificationUuidChildren(_ value: NotificationUuidMO)
@objc(addNotificationUuidChildren:)
@NSManaged public func addToNotificationUuidChildren(_ values: NSSet)
@objc(removeNotificationUuidChildren:)
@NSManaged public func removeFromNotificationUuidChildren(_ values: NSSet)
}
以及通知:
import CoreData
@objc(NotificationUuid)
public class NotificationUuidMO: AlarmMO {
@NSManaged public var notificationUuid: String
@NSManaged public var alarmParent: AlarmMO
}
最佳答案
当看到AlarmMO
模型时,您只需获取AlarmMO
模型,该模型将包含NotificationUuidMO
集合中的notificationUuidChildren
列表。因此不需要单独获取NotificationUuidMO
。
AlarmMO toNotificationUuidMO
是一对多关系。所以你可以从notificationUuidChildren
得到AlarmMO
,从alarmParent
得到NotificationUuidMO
。
要将NotificationUuidMO
添加到notificationUuidChildren
集合,可以使用extension AlarmMO
中给定的核心数据生成访问器。
例子:
let notificationUuid = NotificationUuidMO....
let alarmMO = AlarmMO....
alarmMO.addToNotificationUuidChildren(notificationUuid)//Here your notificationUuid will be added to `notificationUuidChildren` Set and `alarmParent` of your `notificationUuid` will be automatically assigned to `alarmMO`.
关于swift - 从核心数据加载NSManagedObject时,是否可以免费获得其子级?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53605968/