简体   繁体   English

NSDateFormatter内部dispatch_async

[英]NSDateFormatter inside dispatch_async

I'm a bit confused about how the NSDateFormatter can be used inside a dispatch_async. 我对如何在dispatch_async中使用NSDateFormatter感到有些困惑。 I've read that it's not thread safe, but does it mean I have to create a new instance of it every time I use it inside a dispatch_async, or can I use it as a static as my code below shows? 我读过它不是线程安全的,但这是否意味着我每次在dispatch_async中使用它时都必须创建一个新实例,还是可以将其用作静态代码,如下面的代码所示? Since it is a serial queue I guess it cannot be accessed from multiple places at the same time anyway? 由于它是一个串行队列,我想无论如何不能同时从多个位置访问它?

dispatch_async(video_sync_request_operation_processing_queue(), ^{

    static NSDateFormatter *dateFormatter = nil;
    if (!dateFormatter) {
        dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
        [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
        [dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
    }

    ...

});
  1. If it's serial queue You shouldn't worry about thread safety because those tasks will never work concurrently. 如果是串行队列,则不必担心线程安全,因为这些任务永远不会同时运行。

  2. If You want to use the class instance that is not thread safe on concurrent threads You should make an serial queue exclusively for that instance where You will be using it. 如果要在并发线程上使用不是线程安全的类实例,则应为将要使用它的那个实例专门创建一个串行队列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM