问题
I have a coredata object graph relationship of one to many where one Account could have many Logs (Account<->>Logs). My objective is to sort the array of Accounts that i get from the fetch request, based on the child object's value which is a date inside my Log
extension Account {
@NSManaged public var account_id: String?
@NSManaged public var logs: NSSet?
}
extension SalesLogs {
@NSManaged public var created_date: String?
@NSManaged public var is_modified: Bool
}
My attempt was as bellow. I wants to compare the last created_date of each Account, and returns a sorted Accounts array
let fetchData : [Accounts]= try StorageManager.shared.fetchData(entity: "SalesLogs", model: SalesLogs.self)
let sorted array:[Accounts] = fetchData.filter{($0.logs?.allObjects as! [SalesLogs]).map {$0.created_date ?? "" > }.last == [true]}
回答1:
First, you need to determine which of the logs dates you want to sort by. If it's the latest, then you'd need to find it first.
I suggest you update your SalesLogs
to actually deal with dates instead of strings, because you could easily compare dates and find the maximum (i.e latest).
extension SalesLogs {
var createdDate: Date {
let formatter = DateFormater()
formatter.dateFormat = ...
// I'm avoiding an optional Date for simplicity
return formatter.date(from: self.created_date ?? "") ?? Date.distantPast
}
}
Armed with that, you'd need to find the latest date in a set, and use that to sort the array:
let sorted = fetchData.sorted { a, b in
let logsA = a.logs as? Set<SalesLogs>
let logsB = b.logs as? Set<SalesLogs>
// find the latest (aka max) createdDate
let dateA = logsA?.map{ $0.createdDate }.max{ $0 < $1 }
let dateB = logsB?.map{ $0.createdDate }.max{ $0 < $1 }
return (dateA ?? Date.distantPast) < ( dateB ?? Date.distantPast)
}
来源:https://stackoverflow.com/questions/62560606/sort-the-parent-object-based-on-a-child-element-inside-a-nsset-of-the-parent-obj