2015年8月2日 星期日

iOS Swift 筆記 暫存 SharedPreferences StandardUserDefaults

Android的筆記暫存功能為SharedPreferences
iOS相同的功能為NSUserDefaults.standardUserDefaults()
        //儲存在記事本
        let preferencesSave = NSUserDefaults.standardUserDefaults()
        
        preferencesSave.setValue("張三豐", forKey: "name") //儲存字串
        preferencesSave.setBool(true, forKey: "boy") //儲存布林值
        preferencesSave.setDouble(178.5, forKey: "height") //儲存Double
        preferencesSave.setInteger(99, forKey: "year") //儲存int
        //儲存
        let didSave = preferencesSave.synchronize()


        //讀取記事本
        let preferencesRead = NSUserDefaults.standardUserDefaults()
        
        if preferencesRead.objectForKey("name") == nil {
                //  Doesn't exist
                NSLog("NO name", "...")       
        } else {
                let name = preferencesRead.stringForKey("name") //讀取字串
                let boy = preferencesRead.boolForKey("boy") //讀取布林值
                let height = preferencesRead.doubleForKey("height") //讀取Double
                let year = preferencesRead.integerForKey("year") //讀取int
                NSLog("name:\(name!)", "")
        }

參考連結:
http://stackoverflow.com/questions/19206762/equivalent-to-shared-preferences-in-ios

1 則留言 :