4

I have this code:

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()
   }
}

When I implement next function:

func savePosts() {
    let data = NSMutableData()
    let archiver = NSKeyedArchiver(forWritingWithMutableData: data)

    print("\(archiver)")

    archiver.encodeObject(posts, forKey: "Posts")
    archiver.finishEncoding()
    data.writeToFile(dataFilePath(), atomically: true)
}

I have an error:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[PHAsset encodeWithCoder:]: unrecognized selector sent to instance 0x7fb6dc01a050'

Everything worked fine until I added PHAsset to encodeWithCoder function. PHAsset doens conform NSCoder protocol?

1 Answers1

2

There's no need for encapsulation of PHAsset into an object that conforms to NSCoding.

each PHAsset has a .localIdentifier, You can save that as string and when restoring the asset, retrieve the asset with local identifier using fetchAssetCollectionsWithLocalIdentifiers:options:

mosn
  • 311
  • 3
  • 16