从CoreData检索NSDate并将其设置为Swift中的NSDate变量

时间:2016-06-11 12:32:36

标签: ios swift core-data nsdate

我正在尝试在CoreData中存储NSDate,然后检索它并将其应用于变量

@IBOutlet weak var buttonTimer1: UIButton! {
        setTimersDate.zero = NSDate()
        let appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        let context:NSManagedObjectContext = appDel.managedObjectContext

        var buttonTimer1Date = NSEntityDescription.insertNewObjectForEntityForName("TimerDates", inManagedObjectContext: context) as NSManagedObject
        buttonTimer1Date.setValue(setTimersDate.zero, forKey: "dates")

        do {
            try context.save()
        } catch {
            print("Dates saving error")
        }
}

@IBOutlet weak var setTimer1: UIButton! {
        let appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate //Import Appdelegate
        let context:NSManagedObjectContext = appDel.managedObjectContext

        var request = NSFetchRequest(entityName: "TimerDates")
        request.returnsObjectsAsFaults = false

        do {
            print(request[0].buttonTimer1Date)
        } catch {
            print("Cannot request data")
        }
}

这会在控制台上保存并打印当前日期,因此我知道正在存储日期。但是,我想将request[0]设置回NSDate()。

这是可能的,还是我以错误的方式解决这个问题?

干杯。

1 个答案:

答案 0 :(得分:0)

您需要执行获取请求

  let appDel = UIApplication.sharedApplication().delegate as! AppDelegate //Import Appdelegate
  let context = appDel.managedObjectContext
  let request = NSFetchRequest(entityName: "TimerDates")

  do {
      let allDates = try context.executeFetchRequest(request) as! [NSManagedObject]
      if !allDates.isEmpty { print(allDates[0].valueForKey("dates") }
  } catch let error as NSError {
      print("Cannot request data", error)
  }

然而,此代码作为IBOutlet的闭包有点奇怪。