Last active
July 11, 2022 22:35
-
-
Save nubbel/5b0a5cb2bf6a2e353061 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
func encode<T>(var value: T) -> NSData { | |
return withUnsafePointer(&value) { p in | |
NSData(bytes: p, length: sizeofValue(value)) | |
} | |
} | |
func decode<T>(data: NSData) -> T { | |
let pointer = UnsafeMutablePointer<T>.alloc(sizeof(T.Type)) | |
data.getBytes(pointer) | |
return pointer.move() | |
} | |
// Example: | |
enum Result<T> { | |
case Success(T) | |
case Failure | |
} | |
var res: Result<String> = .Success("yeah") | |
var data = encode(res) | |
var decoded: Result<String> = decode(data) | |
switch decoded { | |
case .Failure: | |
"failure" | |
case .Success(let v): | |
"success: \(v)" // => "success: yeah" | |
} |
I have an NSArray of Struct of which I writeToFile after encode each struct. If I read the saved plist in the same instance, I can read the data back perfectly but when I rerun and reload the data, it only partially decodes each struct. What gives?
Awesome; thank you!
It won't work, if you have an array in your struct.
Any reason why you would want to use this over Struct to NSData via NSJSONSerilization?
Yes, this use to work for me too. It works on simple structs but as it get more complex, nil is always returned. Anyone else experience this?
It seems to fail sometimes, returns nil once in a while even without changing anything on the struct
@RollingGoron speed
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I added a little error handling — see here.