UNPKG

1.89 kBPlain TextView Raw
1//
2// RNBranchAgingDictionary.m
3// RNBranch
4//
5// Created by Jimmy Dee on 3/8/17.
6// Copyright © 2017 Branch Metrics. All rights reserved.
7//
8
9#import "RNBranchAgingDictionary.h"
10#import "RNBranchAgingItem.h"
11
12@interface RNBranchAgingDictionary()
13@property (nonatomic) NSMutableDictionary *dictionary;
14@end
15
16@implementation RNBranchAgingDictionary
17
18#pragma mark - Object lifecycle
19
20+ (instancetype)dictionaryWithTtl:(NSTimeInterval)ttl
21{
22 return [[self alloc] initWithTtl:ttl];
23}
24
25- (instancetype)initWithTtl:(NSTimeInterval)ttl
26{
27 self = [super init];
28 if (self) {
29 _ttl = ttl;
30 _dictionary = [NSMutableDictionary dictionary];
31 }
32 return self;
33}
34
35- (instancetype)init
36{
37 @throw nil;
38}
39
40#pragma mark - Methods from NSMutableDictionary
41
42- (void)setObject:(id)anObject forKey:(id<NSCopying>)aKey
43{
44 [self insertItem:anObject forKey:aKey];
45}
46
47- (void)setObject:(id)obj forKeyedSubscript:(id<NSCopying>)key
48{
49 [self insertItem:obj forKey:key];
50}
51
52- (id)objectForKey:(id)aKey
53{
54 return [self itemForKey:aKey];
55}
56
57- (id)objectForKeyedSubscript:(id)key
58{
59 return [self itemForKey:key];
60}
61
62- (void)removeObjectForKey:(id)key
63{
64 [self.dictionary removeObjectForKey:key];
65}
66
67#pragma mark - Internal utilities
68
69- (void)insertItem:(id)obj forKey:(id<NSCopying>)key
70{
71 [self ageItems];
72
73 self.dictionary[key] = [[RNBranchAgingItem alloc] initWithItem:obj];
74}
75
76- (id)itemForKey:(id)key
77{
78 RNBranchAgingItem *item = self.dictionary[key];
79 return item.item;
80}
81
82- (void)ageItems
83{
84 NSTimeInterval now = [NSDate date].timeIntervalSince1970;
85
86 NSArray<NSString *> *keys = self.dictionary.allKeys; // copy of allKeys
87
88 for (NSString *key in keys) {
89 RNBranchAgingItem *item = self.dictionary[key];
90 if ((now - item.accessTime) >= self.ttl) {
91 [self.dictionary removeObjectForKey:key];
92 }
93 }
94}
95
96@end