I understand that in iOS/Swift creating DateFormatters and setting .dateFormats are expensive, I've read a bunch of different takes here on SO and in blogs, but am still unsure of the best way to efficiently deal with DateFormatter and .dateFormat. Specifically I'm working with an app that roughly mimics Apple's iPhone Weather app UI. Dates arrive via API in timeIntervalSince1970/Unix format. On each view controller I'll use one .dateFormat for the current weather e.g. "EEEE, MMM dd, y", another for formatting date in each of 7 cell in the daily weather table view e.g. "EEEE", and another for the hour in 24 cells in a horizontally scrolling collection view e.g. "ha". Users also page through various view controllers for each location they've saved. I haven't noticed much of a performance hit, but I'd really like to ensure I'm being most efficient, and properly thinking this through (e.g. is Singleton the way to go?).
I had created a Singleton with a single DateFormatter as a static variable, and also created a function to set the .dateFormat and .timeZone for the date formatter (see below). I've assumed based on prior reading that if I stick to iOS 10 or later I don't have to worry about thread safety & that it's likely not a concern in this kind of app, anyway.
class Formatter {
static var dateFormatter = DateFormatter()
private init() {}
static func formatTimeForTimeZone(unixDate: TimeInterval, formatString: String, timeZone: String) -> String {
let usableDate = Date(timeIntervalSince1970: unixDate)
self.dateFormatter.dateFormat = formatString
self.dateFormatter.timeZone = TimeZone(identifier: timeZone)
let dateString = self.dateFormatter.string(from: usableDate)
return dateString
}
}
Each time I'd need to set the date in a view or custom cell class, I'd just call the function, passing in appropriate values like this:
let dateString = Formatter.formatTimeForTimeZone(unixDate: someTime, formatString: someFormatString, timeZone: someTimeZone)
Is it correct that this approach doesn't save me much because I'm setting a .formatString at each call (in each cell)? If so, is there a more sound approach? Advanced thanks for setting me straight.