2017-06-22 113 views
0

我想將用戶從UIDatePicker中選擇的時間保存到字符串類型的核心數據實體中(我只是選擇String來適應下面的代碼。目的是稍後使用this code在選定時間發送用戶內部通知。UIDatePicker問題 - 無法正確顯示時間

當用戶選擇20:00並點擊保存按鈕我想20:00顯示。然而相反,它顯示:

<NSDateFormatter: 0x60000024f8a0> 

在表的行中。每次添加時,輸出都像上面那樣,而不是實際顯示的時間。我的目標只是存儲時間,以便我可以向他們發送通知,如this

這裏是按鈕的代碼:

@IBAction func addBobBtnTapped(_ sender: AnyObject) 
    { 
     let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext //creates an object of a property in AppDelegate.swift so we can access it 

     let bob = Bob(context: context) 
     let dateFormatter = DateFormatter() 
     dateFormatter.dateFormat = "hh:mm" 
     dateFormatter.string(from: timeSetbyUser.date) 

     bob.timeToPing = dateFormatter.description 
      //timeSetbyUser.date as NSDate? 

     //Save the data to core data 
     (UIApplication.shared.delegate as! AppDelegate).saveContext() 
     navigationController!.popViewController(animated: true) 
    } 

非常感謝!

回答

2

您需要更換下面兩行:

dateFormatter.string(from: timeSetbyUser.date) 

bob.timeToPing = dateFormatter.description 

有:

bob.timeToPing = dateFormatter.string(from: timeSetbyUser.date) 

不要忽視警告。你應該看到一條警告線:

dateFormatter.string(from: timeSetbyUser.date) 

關於未使用的返回值。這是一條重要線索。

您還應該更改日期格式。在上午/下午使用HH:mm 24小時時間或使用hh:mm a 12小時時間。

+0

作品!非常感謝您的指點和快速回復!我沒有看到任何警告。我錯過了兄弟嗎? – Has

+0

另外,由於您是一位經驗豐富的開發人員,您在上述用於在用戶設置的時間和日期(待編碼)實施通知的方法的建議是什麼?謝謝! – Has