NBRegularExpressionCache.m 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. //
  2. // NBRegularExpressionCache.m
  3. // libPhoneNumber
  4. //
  5. // Created by Paween Itthipalkul on 11/29/17.
  6. // Copyright © 2017 Google LLC. All rights reserved.
  7. //
  8. #import "NBRegularExpressionCache.h"
  9. @interface NBRegularExpressionCache()
  10. @property (nonatomic, strong) NSCache *cache;
  11. @end
  12. @implementation NBRegularExpressionCache
  13. + (instancetype)sharedInstance {
  14. static NBRegularExpressionCache *instance;
  15. static dispatch_once_t token;
  16. dispatch_once(&token, ^{
  17. instance = [[NBRegularExpressionCache alloc] init];
  18. });
  19. return instance;
  20. }
  21. - (instancetype)init {
  22. self = [super init];
  23. if (self != nil) {
  24. _cache = [[NSCache alloc] init];
  25. }
  26. return self;
  27. }
  28. - (NSRegularExpression *)regularExpressionForPattern:(NSString *)pattern error:(NSError **)error {
  29. @synchronized(self) {
  30. NSRegularExpression *cachedObject = [self.cache objectForKey:pattern];
  31. if (cachedObject != nil) {
  32. return cachedObject;
  33. }
  34. NSError *regExError = nil;
  35. NSRegularExpression *regEx = [[NSRegularExpression alloc] initWithPattern:pattern
  36. options:kNilOptions
  37. error:&regExError];
  38. if (regEx == nil && error != nil) {
  39. if (error != NULL) {
  40. *error = regExError;
  41. }
  42. return nil;
  43. }
  44. [self.cache setObject:regEx forKey:pattern];
  45. return regEx;
  46. }
  47. }
  48. @end