我正在开发一个 Swift 项目,其中有两个模型类:PlaylistGroup 和 PlaylistItem。我遇到了一个问题,无法将项目附加到 PlaylistGroup 中的 playlistItems 属性。以下是模型定义:
@Model
class PlaylistGroup {
@Attribute(.unique) var groupNumberID = UUID()
var groupName: String
var playlistModel: PlayListModel?
@Relationship(deleteRule: .cascade, inverse: \PlaylistItem.group)
var playlistItems: [PlaylistItem]?
init(groupName: String) {
self.groupName = groupName
self.playlistItems = playlistItems. // should I write this??
}
}
@Model
class PlaylistItem: Hashable {
var duration: Int?
var tvgId: String?
var tvgName: String?
var tvgCountry: String?
var tvgLanguage: String?
var tvgLogo: String?
var tvgChno: String?
var tvgShift: String?
var groupTitle: String
var seasonNumber: Int?
var episodeNumber: Int?
var kind: String?
var url: URL?
var lastPlay: Date
var group: PlaylistGroup?
init( duration: Int? = nil, tvgId: String? = nil, tvgName: String? = nil, tvgCountry: String? = nil, tvgLanguage: String? = nil, tvgLogo: String? = nil, tvgChno: String? = nil, tvgShift: String? = nil, groupTitle: String, seasonNumber: Int? = nil, episodeNumber: Int? = nil, kind: String? = nil, url: URL? = nil, lastPlay: Date) {
self.duration = duration
self.tvgId = tvgId
self.tvgName = tvgName
self.tvgCountry = tvgCountry
self.tvgLanguage = tvgLanguage
self.tvgLogo = tvgLogo
self.tvgChno = tvgChno
self.tvgShift = tvgShift
self.groupTitle = groupTitle
self.seasonNumber = seasonNumber
self.episodeNumber = episodeNumber
self.kind = kind
self.url = url
self.lastPlay = lastPlay
}
}
我应该使用 self.playlistItems = playlistItems 初始化 PlaylistGroup 初始值设定项中的 playlistItems 属性吗?我注意到,如果没有这个,我无法使用append 方法将数据附加到playlistItems。任何帮助将不胜感激!
谢谢!
您可以使用空数组或 nil 来初始化关系。
self.playlistItems = playlistItems.
对我来说没有意义。
在添加
playlistItems
之前,您必须将 PlaylistGroup
插入模型上下文中。如果您确实愿意,可以在其初始化程序中执行此操作。