简体   繁体   English

使用Core Data设置日期选择器的初始值

[英]Set initial value of a Date Picker using Core Data

I have created two datepickers in which the user can enter their desired date and time. 我创建了两个日期选择器,用户可以在其中输入所需的日期和时间。

datepickers的图像

When the user clicks the save button, the entered values are saved into Core Data using the following code: 当用户单击“保存”按钮时,使用以下代码将输入的值保存到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.

This saves the date as : Nov 4, 2015 And the time as: 11:15 AM Which I then save into Core Data using 这将日期保存为:2015年11月4日以及时间:上午11:15然后我将使用保存到Core Data中

 entry.setValue(dateOfEntry, forKey: "date")

 entry.setValue(timeStarted, forKey: "startTime")

I was wondering if it is possible for me to use these stored values to later set the initial values of a separate set date pickers when the user opens a different view controller. 我想知道当用户打开不同的视图控制器时,我是否可以使用这些存储的值来稍后设置单独的设置日期选择器的初始值。

At the moment you're taking date and time selections that people have made with the picker and converting these to a string, and saving in your core data model as two strings. 目前,您正在选择人们使用选择器进行的日期和时间选择,并将这些选项转换为字符串,并将核心数据模型保存为两个字符串。

A possible problem with this approach is that stringFromDate uses local settings on the device (country, language) to format that string, so for example people running the app in the US will have a different format than people in Germany. 这种方法可能存在的问题是stringFromDate使用设备上的本地设置(国家/地区,语言)来格式化该字符串,因此例如在美国运行应用程序的人将采用与德国人不同的格式。

Probably what you want to do is combine the selections from your date picker and your time picker into a single NSDate , and then save that combined date directly in core data. 您可能想要做的是将日期选择器和时间选择器中的选择组合到单个NSDate ,然后将组合日期直接保存在核心数据中。

It's a little bit more work upfront when you're creating the entity, but you get some benefits: 当你创建实体时,它会提前做一些工作,但你会得到一些好处:

  • don't have to worry about locales from different regions 不必担心来自不同地区的语言环境
  • if you ever wanted you can now apply sorting of values based on your date attribute 如果您曾经想过,现在可以根据您的日期属性应用值排序
  • makes it a lot easier to populate your pickers based off a date returned from a query. 根据查询返回的日期,可以更轻松地填充您的选择器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM