我根据在struct中创建了数据持久层,但是我还需要用struct创建一些realm对象,并将它添加到struct中的另一个Realm对象,比如array。我的意思是这样的:
public struct Publisher {
public let identifier: Int
public let name: String
}
public struct Character {
public let identifier: Int
public let name: String
public let realName: String
var publisherArray: [Publisher]
}
final class PublisherObject: Object {
dynamic var identifier = 0
dynamic var name = ""
override static func primaryKey() -> String? {
return "identifier"
}
}
final class CharacterObject: Object {
dynamic var identifier = 0
dynamic var name = ""
dynamic var realName = ""
var publisherArray: List<PublisherObject>?
override static func primaryKey() -> String? {
return "identifier"
}
}
在上面的指南中,作者只在struct中添加了另一个结构,而不是数组。 我达到了这一点:
extension Character: Persistable {
public init(managedObject: CharacterObject) {
identifier = managedObject.identifier
name = managedObject.name
realName = managedObject.realName
publisherArray = managedObject.publisherArray
.compactMap(Publisher.init(managedObject:))
}
}
但我不知道,我必须在这里输入:
public func managedObject() -> CharacterObject {
let character = CharacterObject()
character.identifier = identifier
character.name = name
character.realName = realName
// here must be something like that, but for array
// character.publisherArray = publisherArray.managedObject()
return character
}
感谢大家的帮助: - )
答案 0 :(得分:1)
不要为每个结构创建重复的类,只需使用Unrealm即可为您处理所有事情。只需使您的结构/枚举符合Realmable
协议即可。您不仅可以保存Structs数组,还可以保存字典,可选类型atc ..
这是一个示例项目,说明如何实现持久性的抽象层:
答案 1 :(得分:0)
我终于解决了我的问题: - )
public func managedObject() -> CharacterObject {
let character = CharacterObject()
character.identifier = identifier
character.name = name
character.realName = realName
publisherArray.forEach({ publisher in
character.publisherArray.append(publisher.managedObject())
})
return character
}