forked from jerrykrinock/ClassesObjC
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSSYCachyAliasResolver.m
106 lines (81 loc) · 2.13 KB
/
SSYCachyAliasResolver.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#import "SSYCachyAliasResolver.h"
#import "NSData+FileAlias.h"
static SSYCachyAliasResolver* sharedResolver = nil ;
@interface SSYCachyAliasResolver ()
@property (retain, readonly) NSMutableDictionary* cache ;
@end
@implementation SSYCachyAliasResolver
- (void)dealloc {
[m_cache release] ;
[super dealloc] ;
}
- (NSMutableDictionary*)cache {
NSMutableDictionary* cache ;
@synchronized(self) {
if (!m_cache) {
m_cache = [[NSMutableDictionary alloc] init] ;
}
cache = [[m_cache retain] autorelease] ;
}
return cache ;
}
+ (SSYCachyAliasResolver*)sharedResolver {
@synchronized(self) {
if (!sharedResolver) {
sharedResolver = [[self alloc] init] ;
}
}
// No autorelease. This sticks around forever.
return sharedResolver ;
}
- (NSString*)pathFromAlias:(NSData*)alias
useCache:(BOOL)useCache
timeout:(NSTimeInterval)timeout
lifetime:(NSTimeInterval)lifetime
error_p:(NSError**)error_p {
if (!alias) {
return nil ;
}
id path = nil ;
NSNumber* key = nil ;
BOOL alreadyInCache = NO ;
// First, try to get from cache if allowed
if (useCache) {
NSUInteger hash = [alias hash] ;
key = [NSNumber numberWithInteger:hash] ;
path = [[self cache] objectForKey:key] ;
alreadyInCache = (path != nil) ;
}
// If not found in cache, try to resolve alias
if (!path) {
path = [alias pathFromAliasRecordWithTimeout:timeout
error_p:error_p] ;
}
// If nothing in cache and could not resolve alias, set to a Null
if (!path) {
path = [NSNull null] ;
}
// Cache the result
if (!alreadyInCache && (lifetime > 0.0)) {
if (!key) {
NSUInteger hash = [alias hash] ;
key = [NSNumber numberWithInteger:hash] ;
}
[[self cache] setObject:path
forKey:key] ;
[NSTimer scheduledTimerWithTimeInterval:lifetime
target:self
selector:@selector(clearCachedPath:)
userInfo:key
repeats:NO] ;
}
if ([path isKindOfClass:[NSNull class]]) {
path = nil ;
}
return path ;
}
- (void)clearCachedPath:(NSTimer*)timer {
NSNumber* key = [timer userInfo] ;
[[self cache] removeObjectForKey:key] ;
}
@end