swift - Saving highscores with NSUserDefaults -
i'm trying save highscore of game. i'm trying via nsuserdefaults
. code i'm using:
//to save highest score var highestscore:int = 20 nsuserdefaults.standarduserdefaults().setobject(highestscore, forkey:"highestscore") nsuserdefaults.standarduserdefaults().synchronize() //to saved score var savedscore: int = nsuserdefaults.standarduserdefaults().objectforkey("highestscore") int println(savedscore)
but error nsuserdefaults
saying "expected declaration" , can't figure out how implement this. or should using nsarchiver
this? , if case how implement this?
use nscoding. create swift file "highscore"
import foundation class highscore: nsobject { var highscore: int = 0 func encodewithcoder(acoder: nscoder!) { acoder.encodeinteger(highscore, forkey: "highscore") } init(coder adecoder: nscoder!) { highscore = adecoder.decodeintegerforkey("highscore") } override init() { } } class savehighscore:nsobject { var documentdirectories:nsarray = [] var documentdirectory:string = "" var path:string = "" func archivehighscore(#highscore: highscore) { documentdirectories = nssearchpathfordirectoriesindomains(.documentdirectory, .userdomainmask, true) documentdirectory = documentdirectories.objectatindex(0) string path = documentdirectory.stringbyappendingpathcomponent("highscore.archive") if nskeyedarchiver.archiverootobject(highscore, tofile: path) { println("success writing file!") } else { println("unable write file!") } } func retrievehighscore() -> nsobject { var datatoretrieve = highscore() documentdirectories = nssearchpathfordirectoriesindomains(.documentdirectory, .userdomainmask, true) documentdirectory = documentdirectories.objectatindex(0) string path = documentdirectory.stringbyappendingpathcomponent("highscore.archive") if let datatoretrieve2 = nskeyedunarchiver.unarchiveobjectwithfile(path) as? highscore { datatoretrieve = datatoretrieve2 } return(datatoretrieve) } }
then viewcontroller:
import uikit class viewcontroller: uiviewcontroller, uitextfielddelegate { var score = highscore() override func viewdidload() { super.viewdidload() score.highscore = 100 savehighscore().archivehighscore(highscore: score) var retrievedhighscore = savehighscore().retrievehighscore() highscore println(retrievedhighscore.highscore) } }
Comments
Post a Comment