【发布时间】:2020-09-28 18:54:53
【问题描述】:
我的 JSON 看起来像这样,它返回 Posts 的列表:
[
{
"id" : 1,
"message": "Hello"
"urls" : {
"png" : "https://example.com/image.png",
"jpg" : "https://example.com/image.jpg",
"gif" : "https://example.com/image.gif"
}
}
]
如您所见,我需要创建两个类。一个用于父对象 (Post),一个用于对象 "urls" (PostUrls)。
我是这样做的:
class Post: Object, Decodable {
@objc dynamic var id = 0
@objc dynamic var message: String? = nil
@objc dynamic var urls: PostUrls? = nil
override static func primaryKey() -> String? {
return "id"
}
private enum PostCodingKeys: String, CodingKey {
case id
case message
case urls
}
convenience init(id: Int, message: String, urls: PostUrls) {
self.init()
self.id = id
self.message = message
self.urls = urls
}
convenience required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: PostCodingKeys.self)
let id = try container.decode(Int.self, forKey: .id)
let message = try container.decode(String.self, forKey: .message)
let urls = try container.decode(PostUrls.self, forKey: .urls)
self.init(id: id, message: message, urls: urls)
}
required init() {
super.init()
}
}
和
@objcMembers class PostUrls: Object, Decodable {
dynamic var png: String? = nil
dynamic var jpg: String? = nil
dynamic var gif: String? = nil
private enum PostUrlsCodingKeys: String, CodingKey {
case png
case jpg
case gif
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: PostUrlsCodingKeys.self)
png = try container.decodeIfPresent(String.self, forKey: .png)
jpg = try container.decodeIfPresent(String.self, forKey: .jpg)
gif = try container.decodeIfPresent(String.self, forKey: .gif)
super.init()
}
required init() {
super.init()
}
}
但是,问题是我在Post 和PostUrls 之间没有关系,因为没有连接两者的主键。此外,这也意味着我目前无法控制 PostUrls 表中的重复项。
所以我的问题是:如何在两个表之间创建关系,并防止PostUrls 表中的重复?
【问题讨论】:
-
我抛出了一个答案来处理你关于人际关系的问题的第一部分。但是,防止重复是一个完全不同的问题。您将如何确定某物是否是重复的 - 重复类型? .jpg、.gif 等或重复的 url 或两者兼而有之……或其他?