Skip to content

Instantly share code, notes, and snippets.

@afterxleep
Last active October 29, 2020 04:54
Show Gist options
  • Save afterxleep/e108b8b9535ca25dcdb0efe26b657de7 to your computer and use it in GitHub Desktop.
Save afterxleep/e108b8b9535ca25dcdb0efe26b657de7 to your computer and use it in GitHub Desktop.
[danielbernal.co] NSSecureCoding + CoreData
class MyTestClass: NSSecureCoding {
var name: String = ""
var last_name: String = ""
// Make sure you add this property
static var supportsSecureCoding: Bool = true
required init?(coder: NSCoder) {
// NSCoding
//name = coder.decodeObject(forKey: "name") as? String ?? ""
//last_name = coder.decodeObject(forKey: "last_name") as? String ?? ""
// NSSecureCoding
name = coder.decodeObject(of: NSString.self, forKey: "name") as String? ?? ""
last_name = coder.decodeObject(of: NSString.self, forKey: "last_name") as String? ?? ""
}
func encode(with coder: NSCoder) {
coder.encode(name, forKey: "name")
coder.encode(last_name, forKey: "last_name")
}
}
// It has to be a subclass of `NSSecureUnarchiveFromDataTransformer` and we need to expose it to ObjC.
@objc(MyTestClassValueTransformer)
final class MyTestClassValueTransformer: NSSecureUnarchiveFromDataTransformer {
// The name of the transformer. This is what we will use to register the transformer `ValueTransformer.setValueTrandformer(_"forName:)`.
static let name = NSValueTransformerName(rawValue: String(describing: MyTestClassValueTransformer.self))
// Our class `Test` should in the allowed class list. (This is what the unarchiver uses to check for the right class)
override static var allowedTopLevelClasses: [AnyClass] {
return [MyTestClass.self]
}
/// Registers the transformer.
public static func register() {
let transformer = MyTestClassValueTransformer()
ValueTransformer.setValueTransformer(transformer, forName: name)
}
}
// ... Make sure to register before initializing your persistent container
// Register the transformer
MyTestClassValueTransformer.register()
// .. Continue initializing Persistent Container
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment