Last active
August 9, 2017 17:11
-
-
Save asowers1/6d8fadb49e62c637769ae318509b6704 to your computer and use it in GitHub Desktop.
Adding Automatic NSCoding for NSObject in Swift
This file contains hidden or 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
// | |
// NSObject+NSCoding.swift | |
// | |
// Created by Andrew Sowers on 6/8/16. | |
// | |
// | |
import Foundation | |
public extension NSObject { | |
func codableProperties() -> Dictionary<String, Any?> { | |
var codableProperties = [String: Any?]() | |
let mirrorOfSelf: _MirrorType = _reflect(self) | |
let numberOfProperties = _reflect(self).count | |
for i in 0..<numberOfProperties { | |
if i == 0 { | |
// super | |
continue; | |
} | |
let (name,some) = mirrorOfSelf[i] | |
codableProperties[name] = unwrap(some.value) | |
} | |
return codableProperties | |
} | |
func unwrap(any: Any) -> Any? { | |
guard let mirror:_MirrorType = _reflect(any) | |
where mirror.disposition != .Optional else { return any } | |
if mirror.count == 0 { return nil } // Optional.None | |
let (_,some) = mirror[0] | |
return some.value | |
} | |
public func decode(coder decoder: NSCoder) { | |
for (key, _) in codableProperties() { | |
let object: AnyObject? = decoder.decodeObjectForKey(key) | |
setValue(object, forKey: key) | |
} | |
} | |
public func encode(aCoder: NSCoder) { | |
for (key, value) in codableProperties() { | |
switch value { | |
case let property as AnyObject: | |
aCoder.encodeObject(property, forKey: key) | |
case let property as Int: | |
aCoder.encodeInt(Int32(property), forKey: key) | |
case let property as Bool: | |
aCoder.encodeBool(property, forKey: key) | |
default: | |
print("Nil value for \(key)") | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment