[英]How can I save and display date picker value in detail text label using core data?
[英]Set initial value of a Date Picker using Core Data
我創建了兩個日期選擇器,用戶可以在其中輸入所需的日期和時間。
當用戶單擊“保存”按鈕時,使用以下代碼將輸入的值保存到Core Data中:
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle
dateFormatter.timeStyle = NSDateFormatterStyle.NoStyle
let timeFormatter = NSDateFormatter()
timeFormatter.dateStyle = NSDateFormatterStyle.NoStyle
timeFormatter.timeStyle = NSDateFormatterStyle.ShortStyle
dateOfEntry = dateFormatter.stringFromDate(entryDate.date) //entryDate is the name of the IBOutlet of the first date picker.
timeStarted = timeFormatter.stringFromDate(startTime.date) //startTime is the name of the IBOutlet of the second date picker.
這將日期保存為:2015年11月4日以及時間:上午11:15然后我將使用保存到Core Data中
entry.setValue(dateOfEntry, forKey: "date")
entry.setValue(timeStarted, forKey: "startTime")
我想知道當用戶打開不同的視圖控制器時,我是否可以使用這些存儲的值來稍后設置單獨的設置日期選擇器的初始值。
目前,您正在選擇人們使用選擇器進行的日期和時間選擇,並將這些選項轉換為字符串,並將核心數據模型保存為兩個字符串。
這種方法可能存在的問題是stringFromDate
使用設備上的本地設置(國家/地區,語言)來格式化該字符串,因此例如在美國運行應用程序的人將采用與德國人不同的格式。
您可能想要做的是將日期選擇器和時間選擇器中的選擇組合到單個NSDate
,然后將組合日期直接保存在核心數據中。
當你創建實體時,它會提前做一些工作,但你會得到一些好處:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.