ios - Is it ok to use NSUserDefaults to persist and pass data between ViewControllers -
i came across website blogger recommends not use nsuserdefaults pass data between viewcontrollers method have been using.
this how i'm using nsuserdefaults store user's settings values of app.
1- first thing in main viewcontroller add constant variables of keys able read them globally.
let kone= "keyone" let ktwo = "keytwo" class viewcontroller: uiviewcontroller{ //code... }
2- in appdelegate.swift initialize of key values in didfinishlaunchingwithoptions method.
// set default values nsuserdefaults keys nsuserdefaults.standarduserdefaults().registerdefaults([ kone : "0", ktwo:"0" ])
3- in viewcontroller read values.
func keyonefromdisc()->double{ let keyonevalue:string = nsuserdefaults.standarduserdefaults().stringforkey(kone)! return double(keyonevalue)! } // value...
4- in settingsviewcontroller read , save nsuserdefaults again.
func keyonefromdisc()->double{ let keyonevalue:string = nsuserdefaults.standarduserdefaults().stringforkey(kone)! return double(keyonevalue)! } // more functions... // save settings @ibaction func savesettings(sender: anyobject) { nsuserdefaults.standarduserdefaults().setobject(somevaluefromaninputfield.text, forkey: kone) // more keys }
i bad practice?
what better way accomplish described above?
edit: sorry confusion, forgot mention need persist data i'm passing around. use
prepareforsegue
when passing data around not need persisted.
you can use nsuserdefault
storing less amount of data, login purpose or bool flag etc. every time can't store data transition of viewcontroller.
for purpose can use
-(void)prepareforsegue:(uistoryboardsegue *)segue sender:(id)sender
Comments
Post a Comment