UserDefaults不会加载

时间:2018-06-22 04:02:16

标签: iphone xcode nsuserdefaults

我有一个VC,它可以将名称传递给第二个视图控制器上的标签:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destination = segue.destination as? ViewController{
        destination.name = petNameTxt.text
        destination.morning = morningFeed.text
        destination.night = nightFeed.text
    }
}

在第二个VC上,我尝试保存标签,但它只在UserDefaults中保存占位符文本:

将其保存在ViewDidLoad

let userDefaults = UserDefaults.standard
        userDefaults.setValue(petNameLbl.text, forKey: "data")
        userDefaults.synchronize()

将其加载到与ViewDidLoad一起运行的单独函数中

let defaults = UserDefaults.standard
    if let name = defaults.string(forKey: "data"){
        petNameLbl.text = name
    }

1 个答案:

答案 0 :(得分:0)

不确定您的问题是什么,但这是一个更合适的(INMNSHO)解决方案:

保存值的代码:

    AlarmManager alarmMgr0 = 
    (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    Intent intent0 = new Intent(this,schedule.class);
    PendingIntent pendingIntent0 = PendingIntent.getBroadcast(this, 0, 
    intent0, 0);
    // Intent intent0 = new Intent(this, OldEntryRemover.class);
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 32);
    calendar.set(Calendar.SECOND, 0);
    //set that timer as a RTC Wakeup to alarm manager object
    alarmMgr0.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 
    pendingIntent0);

获取值的代码

Thread.current.threadDictionary["data"] = petNameLbl.text