ios - Swift NSUserDefaults app crash first time -
my app crash every time installed it, first time..
this code
var state = save.stringforkey("statesave") var city = save.stringforkey("citysave") var vehicle = save.stringforkey("modelnumbersave") var extensionperiod = save.stringforkey("extensionperiodchoosed") var location = "location" if extensionperiod == nil { var name = "" var fieldchoosed: void = save.setobject(name, forkey: "extensionperiodchoosed") save.synchronize() } save.synchronize() var detailnames = ["\(state!)","\(city!)","\(location)","\(vehicle!)","\(extensionperiod!)"]
it crash because extensionperiod nil. think it's because of nsuserdefaults in if statement. first idea put save.synchronize var save = nsuserdefaults.standarduserdefaults()
didn't work :\
your app crashes because in line:
var detailnames = ["\(state!)","\(city!)","\(location)","\(vehicle!)","\(extensionperiod!)"]
you using force unwrap operator. need make sure these values aren't nil
before unwrapping them.
from the swift programming language: basics:
trying use ! access non-existent optional value triggers runtime error. make sure optional contains non-nil value before using ! force-unwrap value.
you can provide default values using nil coalescing operator:
var state = save.stringforkey("statesave") ?? "texas" var city = save.stringforkey("citysave") ?? "el paso"
as stylistic note, instance variables should begin lowercase letters. type names should begin uppercase letters.
Comments
Post a Comment