-
Notifications
You must be signed in to change notification settings - Fork 0
/
TLCache.m
78 lines (62 loc) · 1.35 KB
/
TLCache.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
//
// TLCache.m
// Mercatalog
//
// Created by Jon Hjelle on 11/22/08.
// Copyright 2008 Calf Trail Software, LLC. All rights reserved.
//
#import "TLCache.h"
@implementation TLCache
#pragma mark Lifecycle
- (id)init {
self = [super init];
if (self) {
keys = [NSMutableArray new];
objects = [[NSMapTable mapTableWithStrongToStrongObjects] retain];
}
return self;
}
- (void)dealloc {
[keys release];
[objects release];
[super dealloc];
}
#pragma mark Accessors
#ifdef TLCACHE_COUNT
- (void)noteUseOfKey:(id)key {
[keys removeObject:key];
[keys addObject:key];
}
- (void)removeItem {
id victim = [keys objectAtIndex:0];
[objects removeObjectForKey:victim];
[keys removeObject:victim];
}
@synthesize countLimit;
- (void)setCountLimit:(NSUInteger)newCountLimit {
countLimit = newCountLimit;
while (countLimit && [keys count] > countLimit) {
[self removeItem];
}
}
#endif /* TLCACHE_COUNT */
- (id)objectForKey:(id)key {
#ifdef TLCACHE_COUNT
[self noteUseOfKey:key];
#endif
return [objects objectForKey:key];
}
- (void)setObject:(id)object forKey:(id)key {
#ifdef TLCACHE_COUNT
[self noteUseOfKey:key];
id existingObject = [objects objectForKey:key];
if (!existingObject &&
[self countLimit] &&
[objects count] == [self countLimit])
{
[self removeItem];
}
#endif /* TLCACHE_COUNT */
[objects setObject:object forKey:key];
}
@end