Reputation: 37
Please I'm using this extension to get the past time from the date. But I'm seeing memory leak in RelativeDateTimeFormatter() Any suggestions please?
extension Date {
func timeAgoDisplay() -> String {
let formatter = RelativeDateTimeFormatter()
formatter.unitsStyle = .full
return formatter.localizedString(for: self, relativeTo: Date())
}
}
Upvotes: 1
Views: 213
Reputation: 437592
You should generally not worry about negligible amounts of memory that might leak from inside the frameworks. That having been said, you should avoid instantiating unnecessary formatters. E.g., you could create a static
variable and re-use it:
extension Date {
private static var formatter: RelativeDateTimeFormatter = {
let formatter = RelativeDateTimeFormatter()
formatter.unitsStyle = .full
return formatter
}()
func timeAgoDisplay() -> String {
Self.formatter.localizedString(for: self, relativeTo: Date())
}
}
Upvotes: 0