这个话题可能不完全明白,但我会解释我想要实现的目标。
exapmle JSON将如下所示:
{
"name": "SomeName",
"addresses": [
{
"city": "Berlin",
"street": "Dunno"
},
{
"city": "Paris",
"street": "Dunno2"
}
]
}
Realm
个对象:
public final class PlaceObject: Object {
@objc dynamic var name = ""
var addresses = RealmSwift.List<Address>()
override public static func primaryKey() -> String? {
return "name" // It's a wrong primary key, it should be some id / auto incremenet id, for example might be like this.
}
}
public final class AddressObject: Object {
@objc dynamic var city = ""
@objc dynamic var street = ""
override public static func primaryKey() -> String? {
return "city" // Same as above.
}
}
然后按照令人惊讶的教程从类转换为结构Using realm(其中包含协议)
除了保存到1个对象嵌套字典/数组之外,我几乎完成了我想要的一切。
结构如下:
struct Place {
public let name: String
public let addresses: [Address]
}
extension Place : Persistable {
public init(managedObject: ManagedObject) {
name = managedObject.name
addresses = managedObject.addresses
}
public func managedObject() -> PlaceObject {
let placeObj = PlaceObject()
placeObj.name = name
placeObj.addresses = addresses
return placeObj
}
public enum PropertyValue : PropertyValueType {
case name(String)
case addresses([Address])
public var propertyValuePair: PropertyValuePair {
switch self {
case .name(let id):
return ("name", id)
case .addresses(let id):
return ("addresses", id)
}
}
}
public enum Query: QueryType {
case name(String)
public var predicate: NSPredicate? {
switch self {
case .name(let value):
return NSPredicate(format: "name == %@", value)
}
}
public var sortDescriptors: [SortDescriptor] {
return [SortDescriptor(keyPath: "name")]
}
}
}
struct Address {
public let city: String
public let street: String
}
extension Address : Persistable {
public init(managedObject: ManagedObject) {
city = managedObject.city
address = managedObject.address
}
public func managedObject() -> AddressObject {
let addreses = AddressObject()
addreses.city = city
addreses.street = street
return addreses
}
public enum PropertyValue : PropertyValueType {
case city(String)
case street(String)
public var propertyValuePair: PropertyValuePair {
switch self {
case .city(let id):
return ("city", id)
case .street(let id):
return ("street", id)
}
}
}
public enum Query: QueryType {
case city(String)
public var predicate: NSPredicate? {
switch self {
case .city(let value):
return NSPredicate(format: "city == %@", value)
}
}
public var sortDescriptors: [SortDescriptor] {
return [SortDescriptor(keyPath: "city")]
}
}
}
我会得到预期的错误:
error: cannot assign value of type 'List<AddressObject>' to type '[Address]'
addresses = managedObject.addresses
error: cannot assign value of type '[Address]' to type 'List<AddressObject>'
placeObj.addresses = addresses
我的问题是如何将[Address]
类型转换为List<AddressObject>
并以不同的方式匹配模式?
周围工作
有一种方法可以用凌乱的方式做到这一点。不要在PlaceObject
内保存一个禁止的数组,但要为此对象创建一个附加键,并通过此键连接这两个,同时从数据库中重新获取它们。在我看来,这不是一个好方法 - 冗余逻辑。
提前致谢!