Swift - NSCoder和PHAsset

4

我有以下代码:

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。 - Oleg Shamin
1
您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - Larme
我该如何做到这一点? - Oleg Shamin
1个回答

2

不需要将PHAsset封装成符合NSCoding的对象。

每个PHAsset都有一个.localIdentifier,您可以将其保存为字符串,并在恢复资产时使用fetchAssetCollectionsWithLocalIdentifiers:options:通过本地标识符检索资产。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接