ios - How to access elements from an NSObject in swift? -
i've set variables object
import uikit class speedtestresult: nsobject { var testtime: nsdate? }
then in controller set object , pass class store it:
testresult.testtime = nsdate() speedtestmanager().addtestresult(testresult)
i need store object , access elements within in view later, have:
import foundation class speedtestmanager : nsobject { var testresultarray = [nsobject]() func addtestresult(testresult: nsobject) { testresultarray.append(testresult) print("printing testresultarray: \(testresultarray)") } }
but when try print the object
printing testresultarray: [<projectname.speedtestresult: 0x127b85e50>]
how access elements within object , store object , retrieve later use in view?
class testresult : nsobject, nssecurecoding { var testtime: nsdate? override init() { super.init() } @objc required init?(coder decoder: nscoder) { self.testtime = decoder.decodeobjectforkey("testtime") as? nsdate } @objc func encodewithcoder(encoder: nscoder) { encoder.encodeobject(self.testtime, forkey: "testtime") } @objc static func supportssecurecoding() -> bool { return true } override var description: string { return string.init(format: "testresult: %@", self.testtime ?? "null") } } class speedtestmanager : nsobject, nssecurecoding { var testresultarray = [nsobject]() func addtestresult(testresult: nsobject) { testresultarray.append(testresult) print("printing testresultarray: \(testresultarray)") } override init() { super.init() } @objc func encodewithcoder(encoder: nscoder) { encoder.encodeobject(self.testresultarray, forkey: "testresultarray") } @objc required init?(coder decoder: nscoder) { self.testresultarray = decoder.decodeobjectforkey("testresultarray") as! [nsobject] } @objc static func supportssecurecoding() -> bool { return true } override var description: string { return string.init(format: "speedmanager: [%@]", self.testresultarray.map({"\($0)"}).joinwithseparator(",")) } } class testviewcontroller: uiviewcontroller { override func viewdidload() { super.viewdidload() let testresult = testresult() testresult.testtime = nsdate() let speedmanager = speedtestmanager() speedmanager.addtestresult(testresult) nsuserdefaults.standarduserdefaults().setobject(nskeyedarchiver.archiveddatawithrootobject(speedmanager), forkey: "speedmanager") nsuserdefaults.standarduserdefaults().synchronize() if let archivedspeedmanager = nsuserdefaults.standarduserdefaults().objectforkey("speedmanager") as? nsdata { let unarchivedspeedmanager = nskeyedunarchiver.unarchiveobjectwithdata(archivedspeedmanager) print("speedmanager: \(unarchivedspeedmanager ?? "null")") } else { print("failed unarchive speed manager") } } }