【发布时间】:2016-02-26 13:49:45
【问题描述】:
我有这个代码:
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。 -
但是 PHAsset 它是 NSObject
-
NSObject不符合NSCoding。您必须将 PHAsset 封装到允许 NSCoding 的自定义类中。 -
我该怎么做?
标签: iphone swift phasset nscoder