3
我有這樣的代碼:斯威夫特 - NSCoder和PHAsset
import Foundation
import Photos
class PostItem: NSObject, NSCoding {
var postDate: String?
var postTitle: String?
var postText: String?
var postImages: [PHAsset]?
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(postDate, forKey: "postDate")
aCoder.encodeObject(postTitle, forKey: "postTitle")
aCoder.encodeObject(postText, forKey: "postText")
aCoder.encodeObject(postImages, forKey: "postImages")
}
required init?(coder aDecoder: NSCoder) {
postDate = aDecoder.decodeObjectForKey("postDate") as? String
postTitle = aDecoder.decodeObjectForKey("postTitle") as? String
postText = aDecoder.decodeObjectForKey("postText") as? String
postImages = aDecoder.decodeObjectForKey("postImages") as? [PHAsset]
super.init()
}
override init() {
super.init()
}
}
當我實現了一個功能:
func savePosts() {
let data = NSMutableData()
let archiver = NSKeyedArchiver(forWritingWithMutableData: data)
print("\(archiver)")
archiver.encodeObject(posts, forKey: "Posts")
archiver.finishEncoding()
data.writeToFile(dataFilePath(), atomically: true)
}
我有一個錯誤:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[PHAsset encodeWithCoder:]: unrecognized selector sent to instance 0x7fb6dc01a050'
一切工作正常,直到我將PHAsset添加到encodeWithCoder函數中。 PHAsset遵循NSCoder協議?
號只爲'NSObject'和'NSCopying'根據文件與本地標識符檢索資產。 – Larme
但PHAsset是NSObject –
'NSObject'不符合'NSCoding'。您必須將PHAsset封裝到允許NSCoding的自定義類中。 – Larme