Skip to content

Instantly share code, notes, and snippets.

@karwa
Created November 1, 2017 04:57
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karwa/10d517815319610a7dbfa1bfb3be7f10 to your computer and use it in GitHub Desktop.
Save karwa/10d517815319610a7dbfa1bfb3be7f10 to your computer and use it in GitHub Desktop.
codable-nscoding bridge
import Foundation
/// This isn't safe to use before Swift gets ABI stability, because generic classes
/// could change their names. Also, be sure to register bridges with the Obj-C runtime
/// if using to decode during iOS state restoration.
///
class CodableBridge<Wrapped: Codable>: NSObject, NSSecureCoding {
let value: Wrapped
init(_ value: Wrapped) { self.value = value }
static var supportsSecureCoding: Bool { return true }
required init?(coder aDecoder: NSCoder) {
guard let data = aDecoder.decodeData() else { return nil }
let archiver = NSKeyedUnarchiver(forReadingWith: data)
guard let value = archiver.decodeDecodable(Wrapped.self, forKey: "value") else { return nil }
self.value = value
}
func encode(with aCoder: NSCoder) {
let d = NSMutableData()
let archiver = NSKeyedArchiver(forWritingWith: d)
try? archiver.encodeEncodable(value, forKey: "value")
archiver.finishEncoding()
aCoder.encode(d)
}
}
@tmbiOS
Copy link

tmbiOS commented Oct 12, 2018

Hi, Karl!
How to use it?

@w-i-n-s
Copy link

w-i-n-s commented Nov 30, 2018

@karwa How to use it?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment