-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTJReusePool.m
More file actions
82 lines (71 loc) · 1.59 KB
/
TJReusePool.m
File metadata and controls
82 lines (71 loc) · 1.59 KB
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
//
// TJReusePool.h
// TJCollections
//
// Created by Tim Johnsen.
//
#import "TJReusePool.h"
__attribute__((objc_direct_members))
@interface TJReusePool () <NSCacheDelegate>
@end
__attribute__((objc_direct_members))
@implementation TJReusePool {
dispatch_queue_t _queue;
NSCache *_cache;
NSHashTable *_objects;
}
- (instancetype)init
{
return [self initWithThreadSafety:YES];
}
- (instancetype)initWithThreadSafety:(BOOL)threadSafety
{
if (self = [super init]) {
if (threadSafety) {
_queue = dispatch_queue_create(nil, DISPATCH_QUEUE_SERIAL);
}
_cache = [NSCache new];
_cache.delegate = self;
_objects = [NSHashTable weakObjectsHashTable];
}
return self;
}
- (void)pushObject:(id)object
{
[_cache setObject:object forKey:object];
dispatch_block_t block = ^{
[self->_objects addObject:object];
};
if (_queue) {
dispatch_async(_queue, block);
} else {
block();
}
}
- (id)popObject
{
__block id object;
dispatch_block_t block = ^{
object = [self->_objects anyObject];
[self->_objects removeObject:object];
[self->_cache removeObjectForKey:object]; // This ends up invoking -cache:willEvictObject:
};
if (_queue) {
dispatch_sync(_queue, block);
} else {
block();
}
return object;
}
- (void)cache:(NSCache *)cache willEvictObject:(id)obj
{
dispatch_block_t block = ^{
[self->_objects removeObject:obj];
};
if (_queue) {
dispatch_async(_queue, block);
} else {
block();
}
}
@end