Skip to content

Commit

Permalink
Switch NBShortNumberUtil to a singleton pattern.
Browse files Browse the repository at this point in the history
This mirrors NBPhoneNumberUtil API and prevents unnecessary resource usage due to loading of metadata.
  • Loading branch information
egoldfarb committed Jan 27, 2023
1 parent d72f2a8 commit a1ae914
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 8 deletions.
6 changes: 4 additions & 2 deletions libPhoneNumberShortNumber/NBShortNumberUtil.h
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,10 @@ typedef NS_ENUM(NSUInteger, NBEShortNumberCost) {

@property(nonatomic) NSDictionary<NSNumber *, NSArray<NSString *> *> *countryToRegionCodeMap;

/// Initialize short number util with a default metadata helper.
- (instancetype)init;
/// Short number util singleton with a default metadata helper.
+ (NBShortNumberUtil *)sharedInstance;

- (instancetype)init NS_UNAVAILABLE;

/// Initialize short number util with a metadata helper.
/// @param helper A metadata helper.
Expand Down
16 changes: 11 additions & 5 deletions libPhoneNumberShortNumber/NBShortNumberUtil.m
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,17 @@ @implementation NBShortNumberUtil {
NBPhoneNumberUtil *_phoneUtil;
}

+ (NBShortNumberUtil *)sharedInstance {
static NBShortNumberUtil *sharedOnceInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedOnceInstance =
[[self alloc] initWithMetadataHelper:[[NBShortNumberMetadataHelper alloc] init]
phoneNumberUtil:[NBPhoneNumberUtil sharedInstance]];
});
return sharedOnceInstance;
}

- (instancetype)initWithMetadataHelper:(NBShortNumberMetadataHelper *)helper
phoneNumberUtil:(NBPhoneNumberUtil *)phoneNumberUtil {
self = [super init];
Expand All @@ -36,11 +47,6 @@ - (instancetype)initWithMetadataHelper:(NBShortNumberMetadataHelper *)helper
return self;
}

- (instancetype)init {
return [self initWithMetadataHelper:[[NBShortNumberMetadataHelper alloc] init]
phoneNumberUtil:[NBPhoneNumberUtil sharedInstance]];
}

- (BOOL)isPossibleShortNumber:(NBPhoneNumber *)phoneNumber forRegion:(NSString *)regionDialingFrom {
if (![self doesPhoneNumber:phoneNumber matchesRegion:regionDialingFrom]) {
return NO;
Expand Down
2 changes: 1 addition & 1 deletion libPhoneNumberShortNumber/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ import libPhoneNumberShortNumber

## Usage - **NBShortNumberUtil**
```obj-c
NBShortNumberUtil *shortNumberUtil = [[NBShortNumberUtil alloc] init];
NBShortNumberUtil *shortNumberUtil = [NBShortNumberUtil sharedInstance];

// possibleNumber : +33123456
NSLog(@"Is possible short number: %d",
Expand Down

0 comments on commit a1ae914

Please sign in to comment.