在用户默认值swift

时间:2018-03-14 09:15:01

标签: ios swift nsuserdefaults

我是swift的新手,并试图找出存储用户默认值的最佳方式。以下是我的应用程序的3个初始VC类,其中我将数据从登机视图传递到开始您的计划视图,再到用户信息(配置文件视图) - 这是我需要为用户存储默认值的地方。我的问题是 - 存储的唯一用户默认值是" name"和"每月"薪水似乎也有效。但是"每日预算默认"和"每日储蓄违约" (这些是双打)似乎不存储并出现在第3个屏幕上(用户个人资料)。我没有得到正确的参考。

代码的第一个代码段来自登机视图控制器,我收集他们的信息 - 为了保持简短,我只显示calculateData IBAction。截至目前 - 这是我试图获取用户默认值的地方。

第二个VC 的信息是登机后的视图,用户可以查看他们的信息 - 一旦他们从这个VC开始按下我创建一个新的用户对象(我应该创建一个新的User对象数组并将其存储在NSUserDefaults下吗?)

第三个VC - 这是实际的用户个人资料,我需要显示所有用户默认值。我将把它设置为初始视图控制器&在app delegate中设置,如果用户之前已经完成了登机屏幕,则首先加载此页面。

请感谢您的帮助!

 import UIKit

 class ViewController: UIViewController, UITextFieldDelegate{

   @IBAction func calculateDataButtonPressed(_ sender: UIButton) {

    customerName = nameTextField.text!


    if let payTotal = Double(monthlyAmountTextField.text!){
        monthlyEarning = payTotal
    }

    if let savingsNumber = Double(desiredSavingsTextField.text!){
        desiredSavingsAmount = savingsNumber

    }

    else {
        displayLabel.text = "Enter input as so: 1299.39"

    }


    budgetForEachDay = ((monthlyEarning - desiredSavingsAmount) / 4.0) / 7.0
    savingsForEachDay = (desiredSavingsAmount / 4.0) / 7.0


    UserDefaults.standard.set(nameTextField.text, forKey: "name")
    UserDefaults.standard.set(monthlyAmountTextField.text, forKey: "monthlyPay")
    UserDefaults.standard.set(savingsForEachDay, forKey: "dailySavingsDefault")
    UserDefaults.standard.set(budgetForEachDay, forKey: "dailyBudgetDefault")
    //THE 4 USER DEFAULTS I NEED TO SAVE 

这是SEGUE LOADS的NEXT类,我在这里创建一个新的User对象 - 我是否应该将用户默认值存储在newUserObject数组中,而不是我试图去做它?

import UIKit

class StartYourPlanViewController: UIViewController {

    var nameFieldPassedOver : String?
    var monthlyEarningPassedOver : Double?
    var desiredSavingsPassedOver : Double?
    var budgetToSpend : Double = 55.3
    var saveEachDay : Double = 55.5



    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var monthtlyEarningLabel: UILabel!
    @IBOutlet weak var desiredSavingsLabel: UILabel!


    override func viewDidLoad() {
        super.viewDidLoad()

        nameLabel.text = nameFieldPassedOver

        monthtlyEarningLabel.text = "\(monthlyEarningPassedOver!)" 
        monthtlyEarningLabel.isHidden = true

        desiredSavingsLabel.text = "\(desiredSavingsPassedOver!)"
        desiredSavingsLabel.isHidden = true


    }


    func makeNewUserObject(){

        let newUser = UserInfo(name: nameFieldPassedOver!, iWantToSave : desiredSavingsPassedOver!, monthlyIncome: monthlyEarningPassedOver!, budgetEachDay : budgetToSpend, youSaveEachDay : saveEachDay)


        newUser.printUserBio()

    }


    @IBAction func startPlanButtonPressed(_ sender: UIButton) {


        makeNewUserObject()



        performSegue(withIdentifier: "GoToYourUserInfoView", sender: self)

    }
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {


       if segue.identifier == "GoToYourUserInfoView"{

           let userInfoVC = segue.destination as! UserInfoViewController


            userInfoVC.userNamePassedOver = nameFieldPassedOver
            userInfoVC.userDailyBudgetPassedOver = budgetToSpend
            userInfoVC.userMonthlyEarningsPassedOver = monthlyEarningPassedOver
            userInfoVC.userDesiredSavingsPassedOver = desiredSavingsPassedOver
            userInfoVC.userDailySavingsPassedOver = saveEachDay

        }

    }


}

这将最终成为我的主要和初始VC-我显示他们的用户信息。我需要设置用户默认值的默认值,以便每次现有用户打开应用时它们都会显示在此页面上

class UserInfoViewController : ViewController {

    var userNamePassedOver : String?
    var userDailyBudgetPassedOver : Double?
    var userDailySavingsPassedOver : Double?
    var userMonthlyEarningsPassedOver : Double?
    var userDesiredSavingsPassedOver : Double?
    var newAmountPassedBack : Double = 0.0

    let monthlyPay = "monthlyPay"
    let name = "name"
    let dailySavingsDefault = "dailySavingsDefault"
    let dailyBudgetDefault = "dailyBudgetDefault"


    @IBOutlet weak var dailySavingsNumberLabel: UILabel!
    @IBOutlet weak var userNameLabel: UILabel!
    @IBOutlet weak var dailySpendingLimitLabel: UILabel!


    override func viewDidLoad() {
        super.viewDidLoad()



        if let name = UserDefaults.standard.value(forKeyPath: name) as? String{
            userNameLabel.text = name
        }

        if let monthlyPay = UserDefaults.standard.value(forKeyPath: monthlyPay) as? String{

            userMonthlyEarningsPassedOver = Double(monthlyPay)

        }

      if let dailySavingsDefault = UserDefaults.standard.value(forKeyPath: dailySavingsDefault) as? String{



            dailySavingsNumberLabel.text = dailySavingsDefault



        }

       if let dailyBudgetDefault = UserDefaults.standard.value(forKeyPath: dailyBudgetDefault) as? String {

            dailySpendingLimitLabel.text = dailyBudgetDefault


        }


    }

3 个答案:

答案 0 :(得分:4)

最初,您必须将对象存档到NSData中,然后我们可以将其保存到UserDefault,并在需要时从UserDefault中检索它。

示例如下所示: -

1)将对象保存到UserDefault

let groups = [Group(id: 1, name: "group1", shortname: "g1"), Group(id: 2, name: "group2", shortname: "g2")]

var userDefaults = UserDefaults.standard
let encodedData: Data = NSKeyedArchiver.archivedData(withRootObject: groups)
userDefaults.set(encodedData, forKey: "groups")
userDefaults.synchronize()

2)从UserDefault中检索对象

let decoded  = userDefaults.object(forKey: "groups") as! Data
let decodedGroups = NSKeyedUnarchiver.unarchiveObject(with: decoded) as! [Group]

答案 1 :(得分:0)

当您将数据设置为userdefault后,您必须同步userdefault,以便userdefault保存待处理数据。确保userdefault标识符不会出现拼写错误。

答案 2 :(得分:0)

如果您想在 UserDefaults 上存储结构:

// Save the selected timeZone on UserDefaults
    if let encodedCity = try? JSONEncoder().encode(cityAndTimeZone) {
       UserDefaults.standard.set(encodedCity, forKey: "cityAndTimeZone")
    }


// To restore struct from UserDefaults
if let decodedData = UserDefaults.standard.object(forKey: "cityAndTimeZone") as? Data {
        if let cityAndTimeZone = try? JSONDecoder().decode(CityAndTimeZone.self, from: decodedData) {
            timezoneLabel.text = cityAndTimeZone.city
        }
    }