I'm trying to sort a UITableView by Date, that's coming from core data.
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
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. 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. Use a sort descriptor on your fetch request. For your property aDatum
, you'd use something like
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
.
您可以这样操作:
let sortedMeetingData = meetingData.sorted{ $0.meetingDate < $1.meetingDate }
Thanks to Moe, for the quick answer. 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
....
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.