i have following struct:
struct identity { var id: int var createdat: nsdate var string: string var apnstoken: string } over course of application's execution, instances (?) of struct turned nsdata (using following code) , stored in nsuserdefaults:
var id = identity(id: 0, createdat: nsdate(), string: "string", apnstoken: "<apns-token-here>") var data = nsdata(bytesnocopy: &id, length: sizeof(identity),freewhendone:false) when try struct nsdata instance, crashes exc_bad_access (it's code 1):
var id = unsafepointer<identity>(userdefaultsdata.bytes).memory however, happens when nsdata instance nsuserdefaults. if below, works without crash.
var id = identity(id: 0, createdat: nsdate(), string: "string", apnstoken: "<apns-token-here>") var data = nsdata(bytesnocopy: &id, length: sizeof(identity),freewhendone:false) var idprime = unsafepointer<identity>(data.bytes).memory the assembly code dumped exc_bad_access somewhere halfway through objc_retain, after and instruction.
update:
i wasn't honest. data retrieved keychain in objc, bridge_transfer cast nsdata cf data object. cf object comes secitemcopy() out param. thought nsuserdefaults more relatable.
this because line:
var data = nsdata(bytesnocopy: &id, length: sizeof(identity),freewhendone:false) will not render strings (or other type allocates own memory, array) byte form. instead serialize pointer string’s memory nsdata bytes.
this going lead explosions if memory no longer there. why might seem working when in 1 go, not when store user defaults , then, later or maybe in different process, out.
instead, you’ll need store strings own nsdata objects (say nsdata(base64encodedstring:options:)) , store too.