Last active
August 29, 2023 23:19
-
-
Save rudedogdhc/0ae51a8e97a350458386fd914f0f9874 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
public protocol ValueTransforming: NSSecureCoding { | |
static var valueTransformerName: NSValueTransformerName { get } | |
} | |
public class NSSecureCodingValueTransformer<T: NSObject & ValueTransforming>: ValueTransformer { | |
public override class func transformedValueClass() -> AnyClass { T.self } | |
public override class func allowsReverseTransformation() -> Bool { true } | |
public override func transformedValue(_ value: Any?) -> Any? { | |
guard let value = value as? T else { return nil } | |
return try? NSKeyedArchiver.archivedData(withRootObject: value, requiringSecureCoding: true) | |
} | |
public override func reverseTransformedValue(_ value: Any?) -> Any? { | |
guard let data = value as? NSData else { return nil } | |
let result = try? NSKeyedUnarchiver.unarchivedObject( | |
ofClass: T.self, | |
from: data as Data | |
) | |
return result | |
} | |
/// Registers the transformer by calling `ValueTransformer.setValueTransformer(_:forName:)`. | |
public static func registerTransformer() { | |
let transformer = NSSecureCodingValueTransformer<T>() | |
ValueTransformer.setValueTransformer(transformer, forName: T.valueTransformerName) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A value transformer for any object that implements
NSSecureCoding
. Useful for things such as Core Data entities with transformable attributes. To use:Ensure that your object adopts
ValueTransforming
and returns a valid name:Register the transformer before fetching or creating the entity that has a transformable attribute, such as in
application(_:didFinishLaunchingWithOptions:)
:Specify the transformer name in your Core Data model to be
UIColorValueTransformer
, which is the name you specified when adopting theValueTransforming
protocol.