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 2bf05f1
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 7 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

0 comments on commit 2bf05f1

Please sign in to comment.