简体   繁体   English

按日期从核心数据中对TableView进行排序-Swift4

[英]Sort TableView by Date from core Data - Swift4

I'm trying to sort a UITableView by Date, that's coming from core data. 我正在尝试按日期对UITableView进行排序,这是来自核心数据。

Getting data from core data 从核心数据获取数据

func getData() {
    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    do {
    tasks = try context.fetch(Task.fetchRequest())
    }
    catch{
        print("Fetching Failed")
    }
}

Giving data out 提供数据

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "customCell") as! CustomTableViewCell

    let task = tasks[indexPath.row]


    let dateRangeStart = Date()
    let dateRangeEnd = task.Datum
    let components = Calendar.current.dateComponents([.year, .weekOfYear, .month, .day], from: dateRangeStart, to: dateRangeEnd!)


    cell.name.text = task.name
    cell.dayLeft.text = "\(components.month ?? 0)M \(components.weekOfYear ?? 0)W \(components.day ?? 0)D"

    return cell
}

I tried things i found on stackoverflow like 我尝试了在stackoverflow上发现的东西

meetingsData.sort({ $0.meetingDate.compare($1.meetingDate) == .OrderedAscending })

But I did not get it to work.. I'm quiet new to Swift/Programming so if someone could help me there. 但是我没有让它工作。.我是Swift / Programming的新手,所以如果有人可以在我这里帮助我。 I think its cause of my "Array design" 我认为这是我“阵列设计”的原因

You can fetch the data and sort the resulting array. 您可以获取数据并对结果数组进行排序。 But since you're using Core Data, you could just tell Core Data to give you a sorted array in the first place. 但是由于您使用的是Core Data,因此您可以只告诉Core Data首先给您排序数组。 Use a sort descriptor on your fetch request. 在提取请求上使用排序描述符。 For your property aDatum , you'd use something like 对于属性aDatum ,您将使用类似

let sortDescriptor = NSSortDescriptor(key: "aDatum", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor]

Then when you do your fetch, the resulting array will already be sorted by aDatum . 然后,当您执行提取操作时,结果数组将已经按aDatum排序。

您可以这样操作:

let sortedMeetingData = meetingData.sorted{ $0.meetingDate < $1.meetingDate }

Thanks to Moe, for the quick answer. 感谢Moe的快速解答。 That's my solution now. 那是我现在的解决方案。

let sortedData = tasks.sorted{ $0.aDatum! < $1.aDatum! }

let sort = sortedData[indexPath.row]

Now the Array is sorted by Date - Give out Data: 现在,该数组按日期排序-发出数据:

cell.name.text = sort.name
cell.lable.text = sort.lable
....

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

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