Based on the previous discussion I had in SO (see Doubts about concurrency with objects that can be used several times, such as formatting ), here I ask a more theoretical question about objects that are created once during the application life cycle (and never change, therefore, are read-only) and can be accessed from different threads. A simple option is Core Data. Formats can be used in different streams (main stream, import stream, etc.).
NSFormatters, for example, are extremely expensive to create. Based on this, they can be created once, and then reused. A typical template that can be executed (also highlighted by @mattt in NSFormatter is as follows.
+ (NSNumberFormatter *)numberFormatter {
static NSNumberFormatter *_numberFormatter = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_numberFormatter = [[NSNumberFormatter alloc] init];
[_numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
});
return _numberFormatter;
}
Even if I’m sure that this is a very good approach to execution (some object is created that is read-only / immutable), formatters are not thread safe, so using them in thread safe mode can be dangerous. I found a discussion of the argument in NSDateFormatter crash when used from different threads , where the author noticed that a crash could happen.
NSDateFormatters are not thread safe; there was a background thread trying to use the same formatter at the same time (hence the randomness).
, ? ?