是否可以在Swift中创建可选的初始化参数,这样我就可以使用API调用返回的值从JSON创建一个对象,但是当我稍后保存该对象时,我也可以保存下载的UIImage我之前收到的一个网址。
示例:
class Story: NSObject, NSCoding {
var id: Int?
var title, coverImageURL: String?
var coverImage: UIImage?
required init?(anId: Int?, aTitle: String?, aCoverImageURL: String?) {
self.id = anId
self.title = aTitle
self.coverImageURL = aCoverImageURL
}
convenience init?(json: [String: Any]) {
let id = json["id"] as? Int
let title = json["title"] as? String
let coverImageURL = json["cover_image"] as? String
self.init(
anId: id,
aTitle: title,
aCoverImageURL: coverImageURL,
)
}
然后我想将对象保存到内存
//MARK: Types
struct PropertyKey {
static let id = "id"
static let title = "title"
static let coverImageURL = "coverImageURL"
static let coverImage = "coverImage"
}
//MARK: NSCoding
func encode(with aCoder: NSCoder) {
aCoder.encode(id, forKey: PropertyKey.id)
aCoder.encode(title, forKey: PropertyKey.title)
aCoder.encode(coverImageURL, forKey: PropertyKey.coverImageURL)
aCoder.encode(coverImage, forKey: PropertyKey.coverImage)
}
required convenience init?(coder aDecoder: NSCoder) {
guard let id = aDecoder.decodeObject(forKey: PropertyKey.id) as? Int else {
os_log("Unable to decode the id for a Story object.", log: OSLog.default, type: .debug)
return nil
}
guard let title = aDecoder.decodeObject(forKey: PropertyKey.title) as? String else {
os_log("Unable to decode the title for a Story object.", log: OSLog.default, type: .debug)
return nil
}
let coverImageURL = aDecoder.decodeObject(forKey: PropertyKey.coverImageURL) as? String
let coverImage = aDecoder.decodeObject(forKey: PropertyKey.coverImage) as? UIImage
self.init(
anId: id,
aTitle: title,
aCoverImageURL: coverImageURL,
coverImage: coverImage,
)
}
这有意义吗?我希望能够在从API获得响应后立即保存Story对象,但稍后当我将故事保存到内存时,我希望能够为coverImage保存已获取的UIImage。
我该怎么做?
答案 0 :(得分:0)
我不确定为什么没有人对这个答案采取简单的观点,但答案是简单地使你的属性选项,然后你可以设置一个值,或者为零。您还可以创建便利初始值设定项,如果需要,可以自动将某些值设置为nil。因此,以我的应用程序为例,我有一个从API调用构建的模型。该模型具有id
,created_at
等值,在将记录保存到服务器之前不存在,但我在本地创建对象,存储它们,最后将它们发送到服务器,所以我需要能够仅在从JSON创建对象时设置上述值,所以这就是我所做的:
class Story: NSObject, NSCoding {
var id: Int?
var title, coverImageURL: String?
var coverImage: UIImage?
required init?(anId: Int?, aTitle: String?, aCoverImageURL: String?) {
self.id = anId
self.title = aTitle
self.coverImageURL = aCoverImageURL
}
convenience init?(json: [String: Any]) {
let id = json["id"] as? Int
let title = json["title"] as? String
let coverImageURL = json["cover_image"] as? String
self.init(
anId: id,
aTitle: title,
aCoverImageURL: coverImageURL,
)
}
convenience init?(aTitle: String, aCoverImage: UIImage?) {
let title = aTitle
let subtitle = aSubtitle
let coverImage = aCoverImage
let isActive = activeStatus
self.init(
anId: nil,
aTitle: title,
aCoverImageURL: nil,
aCoverImage: coverImage,
)
}
如您所见,我在本地创建对象时只设置了两个值,而其他值只设置为nil
。要允许将值设置为nil
,请在设置时将其设置为可选。简单!