【问题标题】:Swift - NSCoder and PHAssetSwift - NSCoder 和 PHAsset
【发布时间】: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 协议?

【问题讨论】:

  • 没有。根据文档,仅限 NSObjectNSCopying
  • 但是 PHAsset 它是 NSObject
  • NSObject 不符合 NSCoding。您必须将 PHAsset 封装到允许 NSCoding 的自定义类中。
  • 我该怎么做?

标签: iphone swift phasset nscoder


【解决方案1】:

无需将PHAsset 封装到符合NSCoding 的对象中。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-31
    • 2016-12-18
    • 1970-01-01
    • 2018-02-27
    • 1970-01-01
    • 2014-10-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多