我的swift代码是使用核心数据来保存日期和时间的,我想做的是在调试区打印保存的两个日期之间的时间差,然后在tableview视图单元格中显示。我想做的是在调试区打印保存的两个日期之间的时间差,然后显示在tableview视图单元中。gif显示的是核心数据的前两个条目。所以在调试区应该打印3秒。
import UIKit;import CoreData
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var timerz = Timer()
var timeLabel = UITextField()
var theScores = UITableView()
var submit = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.green
theScores.delegate = self
theScores.dataSource = self
timeLabel.textAlignment = .center
[timeLabel,theScores,submit].forEach { (
view.addSubview($0),
$0.translatesAutoresizingMaskIntoConstraints = false
)
}
timerz = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector:#selector(self.tick) , userInfo: nil, repeats: true)
timeLabel.backgroundColor = UIColor.brown
submit.backgroundColor = UIColor.brown
submit.addTarget(self, action:#selector(handleRegisterb2), for: .touchDown)
theScores.register(UITableViewCell.self, forCellReuseIdentifier: "MyCell")
submit.setTitle("Submit", for: .normal)
theScores.contentInset = UIEdgeInsets.zero
NSLayoutConstraint.activate ([
timeLabel.topAnchor.constraint(equalTo: view.centerYAnchor, constant : -265),
timeLabel.trailingAnchor.constraint(equalTo: view.centerXAnchor, constant :150),
timeLabel.widthAnchor.constraint(equalToConstant: 120),
timeLabel.heightAnchor.constraint(equalToConstant: 40),
submit.topAnchor.constraint(equalTo: view.centerYAnchor, constant : -180),
submit.trailingAnchor.constraint(equalTo: view.centerXAnchor, constant :60),
submit.widthAnchor.constraint(equalToConstant: 120),
submit.heightAnchor.constraint(equalToConstant: 40),
theScores.topAnchor.constraint(equalTo: view.topAnchor, constant: 360),
theScores.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0),
theScores.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0),
theScores.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0),
])
}
@objc func handleRegisterb2(sender: UIButton){
enterData()
performAction()
}
func enterData() {
performAction()
let appDeldeaget = UIApplication.shared.delegate as! AppDelegate
let context = appDeldeaget.persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "Data", in: context)
let theTitle = NSManagedObject(entity: entity!, insertInto: context)
theTitle.setValue(timeLabel.text, forKey: "atBATS")
do {
try context.save()
itemName.append(theTitle)
}
catch {
}
self.theScores.reloadData()
}
func performAction() {
let appD = UIApplication.shared.delegate as! AppDelegate
let context = appD.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Data")
request.returnsObjectsAsFaults = false
do {
let result = try context.fetch(request)
var retrievedData = [Double]()
for data in result as! [NSManagedObject] {
if let value = data.value(forKey: "atBATS") as? String {
retrievedData.append(Double(value) ?? 0)
}
/////
}
let arraySum = retrievedData.reduce(0, +)
print(arraySum)
} catch {
print("Failed")
}
}
var itemName : [NSManagedObject] = []
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return itemName.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let title = itemName[indexPath.row]
let cell = theScores.dequeueReusableCell(withIdentifier: "MyCell", for : indexPath)
cell.textLabel!.numberOfLines = 1
cell.selectionStyle = .default
let attr1 = title.value(forKey: "atBATS") as? String
let text = [" : ", attr1].flatMap { $0 }.reduce("", +)
cell.textLabel?.text = "Game \(indexPath.row+1) \(text)"
cell.textLabel?.textAlignment = .center
cell.layoutMargins = UIEdgeInsets.zero
cell.preservesSuperviewLayoutMargins = false
cell.separatorInset = UIEdgeInsets.zero
cell.layoutMargins = UIEdgeInsets.zero
return cell
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == UITableViewCell.EditingStyle.delete {
let appd = UIApplication.shared.delegate as! AppDelegate
let context = appd.persistentContainer.viewContext
context.delete(itemName[indexPath.row])
itemName.remove(at: indexPath.row)
do {
try context.save()
}
catch {
print("d")
}
self.theScores.reloadData()
performAction()
}
}
@objc func tick() {
timeLabel.text = DateFormatter.localizedString(from: Date(), dateStyle: .medium, timeStyle: .medium)
}
}
你的示例代码没有产生GIF中显示的UI(代码没有显示日期,但GIF显示了),所以有些是我的猜测。
你有一个托管对象的数组。
var itemName : [NSManagedObject] = []
而你得到的管理对象要显示在表格单元格中,并带有
let title = itemName[indexPath.row]
现在,假设这些被管理的对象也有一个日期,你将会得到类似这样的日期
let date = title.valueForKey("date") as? Date
[附带说明一下,虽然 valueForKey
工作,使用自定义的 NSManagedObject
子类,所以你可以有命名和类型化的属性。如果你愿意的话,Xcode会自动生成那个子类]。
[另一个旁白是: itemName
对于管理对象的数组来说,是一个不好的名字。名字通常是一个 String
但是这些都是托管对象,而不是字符串。]
如果你想找出两个管理对象的日期之间的差异,你会在两个对象上查找日期(如上图所示),然后使用 Date
函数来获取差异。
从你的问题中并不清楚 其中 因为你使用的数组可以包含任意数量的对象,所以你要比较的两个对象。对于任何两个对象,日期差将是 类似
iet index1 = 1
let index2 = 2
let object1 = itemName[index1]
let object2 = itemName[index2]
if let date1 = object1.valueForKey("date") as? Date, let date2 = object2.valueForKey("date") as? Date {
let difference = date1.timeIntervalSinceDate(date2)
}
如何选择数值 index1
和 index2
是由你自己决定的。