简体   繁体   中英

NSDateFormatter inside dispatch_async

I'm a bit confused about how the NSDateFormatter can be used inside a dispatch_async. 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? 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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