Cowboy Tech

iOS数据存储-NSUserDefault

读取数据 from NSUserDeafult

var ud:NSUserDefaults!

ud = NSUserDefaults.standardUserDefaults()

    if let value: AnyObject = ud.objectForKey("data"){

        inputTxt.text = value as! String

    }else{

        inputTxt.text = "No value"
    }

保存数据 to NSUserDefaults

ud.setObject(inputTxt.text, forKey: "data")

AnyObject ?

如果发现返回值有问号 AnyObject?,有可能为空。最好先做如下判断

if let value: AnyObject = ud.objectForKey("data"){

    inputTxt.text = value as! String

}else{

    inputTxt.text = "No value"
}

ShowTips proj

Global setting

var ud:NSUserDefaults!
ud = NSUserDefaults.standardUserDefaults()

Get data

mySwitch.on = ud.boolForKey("showTips")

if mySwitch.on{
    UIAlertView(title: "提示", message: "今天要下雨,出门要带雨具哦!", delegate: nil, cancelButtonTitle: "好的").show()
}

Save data

ud.setBool(mySwitch.on, forKey: "showTips")