2016-06-11 29 views
0

我试图存储一个NSDate在CoreData,然后检索,并把它应用到一个变量检索的NSDate并将其设置为一个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()。

这是可能的吗?或者我会以这种错误的方式去做?

干杯。

回答

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的关闭是有点怪。

+0

非常感谢 - 我会尝试解决方案!它实际上是从'viewDidLoad()'调用的,我认为把它放在IBOutlet下显示了我想要更清楚地实现的内容。作为一个相对的newby,我可能是错的。我将在未来完全发布我的代码。 – prikkles