Last active
September 28, 2021 03:46
-
-
Save IanKeen/361c5378abdcec3f7f29 to your computer and use it in GitHub Desktop.
A couple of extensions to make working with NSCoding a little nicer using generics
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
extension NSCoder { | |
func encode(key: String, value: AnyObject?) { | |
self.encodeObject(value, forKey: key) | |
} | |
func decode<T>(key: String) -> T? { | |
return self.decodeObjectForKey(key) as? T | |
} | |
} | |
extension NSCoding { | |
func encode() -> NSData { | |
return NSKeyedArchiver.archivedDataWithRootObject(self) | |
} | |
static func decode(data: NSData) -> Self? { | |
return NSKeyedUnarchiver.unarchiveObjectWithData(data) as? Self | |
} | |
} | |
//USAGE: | |
class Foo: NSObject, NSCoding { | |
var string: String | |
var integer: Int? | |
required init(string: String, integer: Int?) { | |
self.string = string | |
self.integer = integer | |
} | |
convenience required init?(coder aDecoder: NSCoder) { | |
self.init( | |
string: aDecoder.decode("string")!, | |
integer: aDecoder.decode("integer") | |
) | |
} | |
func encodeWithCoder(aCoder: NSCoder) { | |
aCoder.encode("string", value: self.string) | |
aCoder.encode("integer", value: self.integer) | |
} | |
} | |
let foo = Foo(string: "foo", integer: .None) | |
let data = foo.encode() | |
let decodedFoo = Foo.decode(data) | |
decodedFoo?.string | |
decodedFoo?.integer |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment