我有以下代码:
static NSDictionary * errorDescriptions = nil;
+ (NSString *) errorsFromCode: (WPErrorCode) code {
if(errorDescriptions == nil) {
errorDescriptions = @{[NSNumber numberWithInt: InvalidCar]: NSLocalizedStringFromTable(@"Car is invalid.", @"WePay", @"validation: invalid car"), ...
}
return [errorDescriptions objectForKey: [NSNumber numberWithInt: code]];
}
我得到建议将上面的代码更改为:
+ (NSString *) errorsFromCode: (WPErrorCode) code {
static NSDictionary * errorDescriptions = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
errorDescriptions = @{[NSNumber numberWithInt: InvalidCar]: NSLocalizedStringFromTable(@"Car is invalid.", @"WePay", @"validation: invalid car"), ...
}
return [errorDescriptions objectForKey: [NSNumber numberWithInt: code]];
}
为什么会这样?为什么我必须使用 dispatch_once?