在Swift中创建NSDateFormatter? [英] Creating an NSDateFormatter in Swift?

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

问题描述

我是新手,并不熟悉Objective-C.有人可以帮我将其转换为Swift吗?我从Ray Wenderlich的最佳iOS惯例中获得了此代码- http://www.raywenderlich.com/31166/25-ios-app-performance-tips-tricks

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

您会将代码放在哪里?它将放入充满全局变量的类文件中吗?

Where would you put this code? Would it go in a class file full of global variables?

- (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. 如果您确实要寻找问题中方法的直接模拟,则可以执行以下操作:

  1. If you're really looking for direct analog to the method in your question, 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)
    }
}

static属性(如全局变量)的默认值具有dispatch_once行为.有关更多信息,请参见文件和初始化在Apple的Swift博客中的条目.

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.

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

Regarding best practices with date formatters, I would suggest:

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

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

  • Cache one formatter per date format;

通过NotificationCenter添加NSLocale.currentLocaleDidChangeNotification的观察者,并在发生这种情况时清除/重置缓存的格式化程序;和

Add observer for NSLocale.currentLocaleDidChangeNotification through the NotificationCenter, and clearing/resetting cached formatters if this occurs; and

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

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.

如果使用DateFormatter解析要与Web服务交换(或存储在数据库中)的日期字符串,则应使用en_US_POSIX区域设置,以避免可能不使用公历的国际用户出现问题.请参见 Apple技术问题与解答#1480 或正在工作 DateFormatter文档中的讨论. (或者在iOS 10和macOS 10.12中,使用 ISO8601DateFormatter .)

If using DateFormatter 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 the "Working With Fixed Format Date Representations" discussion in the DateFormatter documentation. (Or in iOS 10 and macOS 10.12, use ISO8601DateFormatter.)

但是将dateFormatDateFormatter结合使用时,请使用当前语言环境来创建要呈现给最终用户的字符串,而在创建/解析要在应用程序内部使用或要在应用程序内部使用的字符串时,请使用local en_US_POSIX与网络服务交换.

But when using dateFormat with 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.

如果要格式化用户界面的日期字符串,请尽可能避免对dateFormat使用字符串文字来对字符串进行本地化.尽可能使用dateStyletimeStyle.并且,如果必须使用自定义dateFormat,请使用模板来本地化字符串.例如,在Swift 3及更高版本中,您可以使用dateFormat(fromTemplate:options:locale:):

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 and later, you would use dateFormat(fromTemplate:options:locale:):

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

例如,这将自动为美国用户显示"9月5日星期一",而对于英国用户则显示"9月5日星期一".

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

DateFormatter现在在iOS 7和更高版本以及在macOS 10.9和更高版本上运行的64位应用程序中是线程安全的.

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

有关Swift 2的示例,请参见此答案的先前版本.

For Swift 2 examples, see previous revision of this answer.

这篇关于在Swift中创建NSDateFormatter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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