DateFormatter 耗时

2020-10-31  本文已影响0人  幸运者_Lucky

Time Profile 定位到一个倒计时显示, 最后发现是 DateFormatter 耗时

官方建议在频繁使用 DateFormatter 处使用一个单例, 并且订阅时区变化, 在时区变化后做相应的处理.

Creating a date formatter is not a cheap operation. If you are likely to use a formatter frequently, it is typically more efficient to cache a single instance than to create and dispose of multiple instances. One approach is to use a static variable

If you cache date formatters (or any other objects that depend on the user’s current locale), you should subscribe to the NSCurrentLocaleDidChangeNotification notification and update your cached objects when the current locale changes. The code in Listing 3 defines sUserVisibleDateFormatter outside of the method so that other code, not shown, can update it as necessary. In contrast, sRFC3339DateFormatter is defined inside the method because, by design, it is not dependent on the user’s locale settings.

Note: In theory you could use an auto-updating locale (autoupdatingCurrentLocale) to create a locale that automatically accounts for changes in the user’s locale settings. In practice this currently does not work with date formatters.

Date Formatting Guide

上一篇下一篇

猜你喜欢

热点阅读