Home > Software design >  RelativeDateTimeFormatter memory leak
RelativeDateTimeFormatter memory leak

Time:08-24

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())
    }
}

enter image description here

CodePudding user response:

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())
    }
}
  • Related