Swift中NSDateFormatter的最佳做法是什么? [英] Whats the best practice for NSDateFormatter in Swift?

查看:276
本文介绍了Swift中NSDateFormatter的最佳做法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的,我很陌生的客观C.有人可以帮我把它转换成快速吗?我从Ray Wenderlich的最佳iOS实践中获得了这个代码 - http://www.raywenderlich.com / 31166/25-ios-app-performance-tips-tricks



你还会在哪里放这个代码?在一个充满全局变量的类文件中?



如果有人比以前发布的更好的解决方案,我很乐意看到它!

   - (NSDateFormatter *)formatter {
static NSDateFormatter * formatter;
static dispatch_once_t onceToken;
dispatch_once(& onceToken,^ {
_formatter = [[NSDateFormatter alloc] init];
_formatter.dateFormat = @EEE MMM dd HH:mm:ss Z yyyy; // twitter日期格式
});
return formatter;
}


解决方案


  1. 如果您真的在寻求直接模拟您问题中的方法,在Swift 3中,您可以执行以下操作:

      class MyObject {

    //定义静态变量

    private static let formatter:DateFormatter = {
    let formatter = DateFormatter()
    formatter .dateFormat =EEE MMM dd HH:mm:ss Z yyyy
    return formatter
    }()

    //你可以像这样使用它

    func someMethod(date:Date) - > String {
    return MyObject.formatter.string(from:date)
    }
    }

    或在Swift 2中:

      class MyObject {

    // define static变量

    private static let formatter:NSDateFormatter = {
    let formatter = NSDateFormatter()
    formatter.dateFormat =EEE MMM dd HH:mm:ss Z yyyy
    return formatter
    }()

    //你可以像这样使用它

    func someMethod(date:NSDate) - > String {
    return MyObject.formatter.stringFromDate(date)
    }
    }

    static 属性,如全局变量,可以为其默认值享受 dispatch_once 行为。有关详细信息,请参阅 dispatch_once 讨论>文件和初始化条目在Apple的Swift博客中。


  2. 关于日期格式化程序的最佳做法,我建议:




    • 是的,谨慎不要不必要地创建和销毁可能需要再次使用的格式化程序。在WWDC 2012视频中, iOS应用程序性能:响应性,Apple明确鼓励我们




      • 按日期格式缓存一个格式化程序;


      • 添加观察器 NSLocale.currentLocaleDidChangeNotification 在Swift 3( Swift 2中的NSCurrentLocaleDidChangeNotification )中通过 NSNotificationCenter ,如果发生这种情况,则清除/重置缓存的格式化程序;


      • 请注意,重置格式与重新创建一样昂贵,因此避免重复更改格式化程序的格式字符串。




      底线,如果您重复使用相同的日期格式,请尽可能重用日期格式化程序。


    • 如果使用 NSDateFormatter 来解析与Web服务(或存储在数据库中)交换的日期字符串,则应使用 en_US_POSIX locale,以避免可能不使用公历的国际用户出现问题。请参阅 Apple技术问答#1480 。 (或在iOS 10和macOS 10.12中,使用 ISO8601DateFormatter 。)



      但是当使用 dateFormat NSDateFormatter / DateFormatter ,使用当前语言环境创建要呈现的字符串最终用户,但在创建/解析应用程序内部要使用的字符串或与Web服务进行交换时,请使用 en_US_POSIX local。


    • 如果格式化用户界面的日期字符串,请尽可能避免使用 dateFormat 的字符串文字来本地化字符串。使用 dateStyle timeStyle 可以在哪里。如果您必须使用自定义 dateFormat ,请使用模板本地化您的字符串。例如,在Swift 3中,您可以使用 dateFormat(fromTemplate:options:locale:)来代替 E,MMM d code>:

        formatter.dateFormat = DateFormatter.dateFormat(fromTemplate:EdMMM,options:0,locale: Locale.current)

      或在Swift 2中, dateFormatFromTemplate(_:options:区域设置:)

        formatter.dateFormat = NSDateFormatter.dateFormatFromTemplate(EdMMM,options:0 ,locale:NSLocale.currentLocale())

      这将自动显示,例如Mon,Sep 5,而英国用户9月5日。


    • 现在,在iOS 7和更高版本以及运行在MacOS上的64位应用程序, NSDateFormatter 10.9及以后。




I am new to swift and am very unfamiliar with objective C. Could someone help me convert this to swift? I got this code from Ray Wenderlich's best iOS practices - http://www.raywenderlich.com/31166/25-ios-app-performance-tips-tricks

Also where would you put this code? In a class file full of global variables?

If someone has a better solution than one posted below I would love to see it!

- (NSDateFormatter *)formatter {
    static NSDateFormatter *formatter;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _formatter = [[NSDateFormatter alloc] init];
        _formatter.dateFormat = @"EEE MMM dd HH:mm:ss Z yyyy"; // twitter date format
    });
    return formatter;
}

解决方案

  1. If you're really looking for direct analog to the method in your question, in Swift 3 you could do something like:

    class MyObject {
    
        // define static variable
    
        private static let formatter: DateFormatter = {
            let formatter = DateFormatter()
            formatter.dateFormat = "EEE MMM dd HH:mm:ss Z yyyy"
            return formatter
        }()
    
        // you could use it like so
    
        func someMethod(date: Date) -> String {
            return MyObject.formatter.string(from: date)
        }
    }
    

    Or in Swift 2:

    class MyObject {
    
        // define static variable
    
        private static let formatter: NSDateFormatter = {
            let formatter = NSDateFormatter()
            formatter.dateFormat = "EEE MMM dd HH:mm:ss Z yyyy"
            return formatter
        }()
    
        // you could use it like so
    
        func someMethod(date: NSDate) -> String {
            return MyObject.formatter.stringFromDate(date)
        }
    }
    

    The static properties, like globals, enjoy dispatch_once behavior for their default values. For more information, see the dispatch_once discussion at the end of the Files and Initialization entry in Apple's Swift blog.

  2. Regarding best practices with date formatters, I would suggest:

    • Yes, it is prudent to not unnecessarily create and destroy formatters that you're likely to need again. In WWDC 2012 video, iOS App Performance: Responsiveness, Apple explicitly encourages us to

      • Cache one formatter per date format;

      • Add observer for NSLocale.currentLocaleDidChangeNotification in Swift 3 (NSCurrentLocaleDidChangeNotification in Swift 2) through the NSNotificationCenter, and clearing/resetting cached formatters if this occurs; and

      • Note that resetting a format is as expensive as recreating, so avoid repeatedly changing a formatter's format string.

      Bottom line, reuse date formatters wherever possible if you're using the same date format repeatedly.

    • If using NSDateFormatter to parse date strings to be exchanged with a web service (or stored in a database), you should use en_US_POSIX locale to avoid problems with international users who might not be using Gregorian calendars. See Apple Technical Q&A #1480. (Or in iOS 10 and macOS 10.12, use ISO8601DateFormatter.)

      But when using dateFormat with NSDateFormatter/DateFormatter, use the current locale for creating strings to be presented to the end user, but use en_US_POSIX local when creating/parsing strings to be used internally within the app or to be exchanged with a web service.

    • If formatting date strings for the user interface, localize the strings by avoiding using string literals for dateFormat if possible. Use dateStyle and timeStyle where you can. And if you must use custom dateFormat, use templates to localize your strings. For example, rather than hard-coding E, MMM d, in Swift 3, you would use dateFormat(fromTemplate:options:locale:):

      formatter.dateFormat = DateFormatter.dateFormat(fromTemplate: "EdMMM", options: 0, locale: Locale.current)
      

      Or in Swift 2, dateFormatFromTemplate(_:options:locale:):

      formatter.dateFormat = NSDateFormatter.dateFormatFromTemplate("EdMMM", options: 0, locale: NSLocale.currentLocale())
      

      This will automatically show, for example, "Mon, Sep 5" for US users, but "Mon 5 Sep" for UK users.

    • The NSDateFormatter is now thread safe on iOS 7 and later and 64-bit apps running on macOS 10.9 and later.

这篇关于Swift中NSDateFormatter的最佳做法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆