我一直在开展一个项目,使用着一个现有的对象。我正在尝试找到一种简单的方法,在Core Data中保存、检索和删除这些对象的列表。
这是我的对象:
import Foundation
class Book : Codable {
var coverIndex:Int?
var authorName:[String]?
var title:String?
var editionCount:Int?
var firstPublishYear:Int?
var key: String?
var publishPlace:[String]?
var publisher:[String]?
public enum BookResponseCodingKeys: String, CodingKey {
case coverIndex = "cover_i"
case authorName = "author_name"
case editionCount = "edition_count"
case firstPublishYear = "first_publish_year"
case key = "key"
case title = "title"
case publishPlace = "publish_place"
case publisher = "publisher"
}
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: BookResponseCodingKeys.self)
self.coverIndex = try container.decodeIfPresent(Int.self, forKey: .coverIndex)
self.authorName = try container.decodeIfPresent([String].self, forKey: .authorName)
self.editionCount = try container.decodeIfPresent(Int.self, forKey: .editionCount)
self.firstPublishYear = try container.decodeIfPresent(Int.self, forKey: .firstPublishYear)
self.key = try container.decodeIfPresent(String.self, forKey: .key)
self.title = try container.decodeIfPresent(String.self, forKey: .title)
self.publishPlace = try container.decodeIfPresent([String].self, forKey: .publishPlace)
self.publisher = try container.decodeIfPresent([String].self, forKey: .publisher)
}
}
什么是将这个内容保存在Core Data中最直接的方法(或将其映射到Core Data模型)?
Codable
,而是尝试子类化NSObject
和NSCoding
。确保实现encode(with aCoder: NSCoder)
和init?(coder aDecoder: NSCoder)
方法。 - jakecreateUser()
。这只需要运行一次 - 实际上,您可以通过检查retrieveUser()
是否返回nil来确保尚未创建用户。然后使用saveBook(book)
方法保存您的书籍。使用当前函数,您必须逐个执行此操作,但制作一个用于追加批处理的函数应该非常简单。 - jake