Having problems with saving and loading in Swift 3.0 iOS 10 -
i'm new swift , ios programming scene , trying learn bunch of things. app, want save , load 1 integer, having problems, found on stack overflow , internet doesn't seem work on swift 3. app crashes immediately, breaks on:
@iboutlet weak var staticlabel: uilabel!
it says "thread 1: breakpoint 3.5" . , tips appreciated :)
import uikit import avfoundation var player: avaudioplayer? var number = 0 class viewcontroller: uiviewcontroller { @iboutlet weak var staticlabel: uilabel! @iboutlet weak var numberlabel: uilabel! let defaults = userdefaults.standard override func viewdidload() { super.viewdidload() load() } func load() { number = defaults.integer(forkey: "save") numberlabel.text = string(number) } func playsound() { let path = bundle.main.path(forresource: "rightyouare.mp3", oftype: nil) let url = url(fileurlwithpath: path!) { let sound = try avaudioplayer(contentsof: url) player = sound sound.play() } catch { // couldn't load file :( } } @ibaction func minus(_ sender: anyobject) { number = number - 1 numberlabel.text = string(number) defaults.set(number, forkey: "save") } @ibaction func plus(_ sender: uibutton) { playsound() number = number + 1 numberlabel.text = string(number) defaults.set(number, forkey: "save") } }
your line of code
number = defaults.integer(forkey: "save")
user defaults integer key save nil, key not exist @ in user defaults
before load integer user defaults , has set first
if defaults.object(forkey: "save") != nil { number = defaults.integer(forkey: "save") }
this make sure object exists in user defaults before getting it's value
finally load function should be
func load() { if defaults.object(forkey: "save") != nil { number = defaults.integer(forkey: "save") numberlabel.text = string(number) } }
Comments
Post a Comment