forked from SDWebImage/SDWebImage
-
Notifications
You must be signed in to change notification settings - Fork 2
/
SDImageCache.m
340 lines (285 loc) · 10.7 KB
/
SDImageCache.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDImageCache.h"
#import "SDWebImageDecoder.h"
#import <CommonCrypto/CommonDigest.h>
#ifdef ENABLE_SDWEBIMAGE_DECODER
#import "SDWebImageDecoder.h"
#endif
static NSInteger cacheMaxCacheAge = 60*60*24*7; // 1 week
static SDImageCache *instance;
@implementation SDImageCache
#pragma mark NSObject
- (id)init
{
if ((self = [super init]))
{
// Init the memory cache
memCache = [[NSMutableDictionary alloc] init];
// Init the disk cache
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
diskCachePath = [[[paths objectAtIndex:0] stringByAppendingPathComponent:@"ImageCache"] retain];
if (![[NSFileManager defaultManager] fileExistsAtPath:diskCachePath])
{
[[NSFileManager defaultManager] createDirectoryAtPath:diskCachePath
withIntermediateDirectories:YES
attributes:nil
error:NULL];
}
// Init the operation queue
cacheInQueue = [[NSOperationQueue alloc] init];
cacheInQueue.maxConcurrentOperationCount = 1;
cacheOutQueue = [[NSOperationQueue alloc] init];
cacheOutQueue.maxConcurrentOperationCount = 1;
#if TARGET_OS_IPHONE
// Subscribe to app events
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(clearMemory)
name:UIApplicationDidReceiveMemoryWarningNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(cleanDisk)
name:UIApplicationWillTerminateNotification
object:nil];
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_4_0
UIDevice *device = [UIDevice currentDevice];
if ([device respondsToSelector:@selector(isMultitaskingSupported)] && device.multitaskingSupported)
{
// When in background, clean memory in order to have less chance to be killed
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(clearMemory)
name:UIApplicationDidEnterBackgroundNotification
object:nil];
}
#endif
#endif
}
return self;
}
- (void)dealloc
{
[memCache release], memCache = nil;
[diskCachePath release], diskCachePath = nil;
[cacheInQueue release], cacheInQueue = nil;
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}
#pragma mark SDImageCache (class methods)
+ (SDImageCache *)sharedImageCache
{
if (instance == nil)
{
instance = [[SDImageCache alloc] init];
}
return instance;
}
#pragma mark SDImageCache (private)
- (NSString *)cachePathForKey:(NSString *)key
{
const char *str = [key UTF8String];
unsigned char r[CC_MD5_DIGEST_LENGTH];
CC_MD5(str, (CC_LONG)strlen(str), r);
NSString *filename = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12], r[13], r[14], r[15]];
return [diskCachePath stringByAppendingPathComponent:filename];
}
- (void)storeKeyWithDataToDisk:(NSArray *)keyAndData
{
// Can't use defaultManager another thread
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSString *key = [keyAndData objectAtIndex:0];
NSData *data = [keyAndData count] > 1 ? [keyAndData objectAtIndex:1] : nil;
if (data)
{
[fileManager createFileAtPath:[self cachePathForKey:key] contents:data attributes:nil];
}
else
{
// If no data representation given, convert the UIImage in JPEG and store it
// This trick is more CPU/memory intensive and doesn't preserve alpha channel
UIImage *image = [[self imageFromKey:key fromDisk:YES] retain]; // be thread safe with no lock
if (image)
{
#if TARGET_OS_IPHONE
[fileManager createFileAtPath:[self cachePathForKey:key] contents:UIImageJPEGRepresentation(image, (CGFloat)1.0) attributes:nil];
#else
NSArray* representations = [image representations];
NSData* jpegData = [NSBitmapImageRep representationOfImageRepsInArray: representations usingType: NSJPEGFileType properties:nil];
[fileManager createFileAtPath:[self cachePathForKey:key] contents:jpegData attributes:nil];
#endif
[image release];
}
}
[fileManager release];
}
- (void)notifyDelegate:(NSDictionary *)arguments
{
NSString *key = [arguments objectForKey:@"key"];
id <SDImageCacheDelegate> delegate = [arguments objectForKey:@"delegate"];
NSDictionary *info = [arguments objectForKey:@"userInfo"];
UIImage *image = [arguments objectForKey:@"image"];
if (image)
{
[memCache setObject:image forKey:key];
if ([delegate respondsToSelector:@selector(imageCache:didFindImage:forKey:userInfo:)])
{
[delegate imageCache:self didFindImage:image forKey:key userInfo:info];
}
}
else
{
if ([delegate respondsToSelector:@selector(imageCache:didNotFindImageForKey:userInfo:)])
{
[delegate imageCache:self didNotFindImageForKey:key userInfo:info];
}
}
}
- (void)queryDiskCacheOperation:(NSDictionary *)arguments
{
NSString *key = [arguments objectForKey:@"key"];
NSMutableDictionary *mutableArguments = [[arguments mutableCopy] autorelease];
UIImage *image = [[[UIImage alloc] initWithContentsOfFile:[self cachePathForKey:key]] autorelease];
if (image)
{
#ifdef ENABLE_SDWEBIMAGE_DECODER
UIImage *decodedImage = [UIImage decodedImageWithImage:image];
if (decodedImage)
{
image = decodedImage;
}
#endif
[mutableArguments setObject:image forKey:@"image"];
}
[self performSelectorOnMainThread:@selector(notifyDelegate:) withObject:mutableArguments waitUntilDone:NO];
}
#pragma mark ImageCache
- (void)storeImage:(UIImage *)image imageData:(NSData *)data forKey:(NSString *)key toDisk:(BOOL)toDisk
{
if (!image || !key)
{
return;
}
[memCache setObject:image forKey:key];
if (toDisk)
{
if (!data) return;
NSArray *keyWithData;
if (data)
{
keyWithData = [NSArray arrayWithObjects:key, data, nil];
}
else
{
keyWithData = [NSArray arrayWithObjects:key, nil];
}
[cacheInQueue addOperation:[[[NSInvocationOperation alloc] initWithTarget:self
selector:@selector(storeKeyWithDataToDisk:)
object:keyWithData] autorelease]];
}
}
- (void)storeImage:(UIImage *)image forKey:(NSString *)key
{
[self storeImage:image imageData:nil forKey:key toDisk:YES];
}
- (void)storeImage:(UIImage *)image forKey:(NSString *)key toDisk:(BOOL)toDisk
{
[self storeImage:image imageData:nil forKey:key toDisk:toDisk];
}
- (UIImage *)imageFromKey:(NSString *)key
{
return [self imageFromKey:key fromDisk:YES];
}
- (UIImage *)imageFromKey:(NSString *)key fromDisk:(BOOL)fromDisk
{
if (key == nil)
{
return nil;
}
UIImage *image = [memCache objectForKey:key];
if (!image && fromDisk)
{
image = [[[UIImage alloc] initWithContentsOfFile:[self cachePathForKey:key]] autorelease];
if (image)
{
[memCache setObject:image forKey:key];
}
}
return image;
}
- (void)queryDiskCacheForKey:(NSString *)key delegate:(id <SDImageCacheDelegate>)delegate userInfo:(NSDictionary *)info
{
if (!delegate)
{
return;
}
if (!key)
{
if ([delegate respondsToSelector:@selector(imageCache:didNotFindImageForKey:userInfo:)])
{
[delegate imageCache:self didNotFindImageForKey:key userInfo:info];
}
return;
}
// First check the in-memory cache...
UIImage *image = [memCache objectForKey:key];
if (image)
{
// ...notify delegate immediately, no need to go async
if ([delegate respondsToSelector:@selector(imageCache:didFindImage:forKey:userInfo:)])
{
[delegate imageCache:self didFindImage:image forKey:key userInfo:info];
}
return;
}
NSMutableDictionary *arguments = [NSMutableDictionary dictionaryWithCapacity:3];
[arguments setObject:key forKey:@"key"];
[arguments setObject:delegate forKey:@"delegate"];
if (info)
{
[arguments setObject:info forKey:@"userInfo"];
}
[cacheOutQueue addOperation:[[[NSInvocationOperation alloc] initWithTarget:self selector:@selector(queryDiskCacheOperation:) object:arguments] autorelease]];
}
- (void)removeImageForKey:(NSString *)key
{
if (key == nil)
{
return;
}
[memCache removeObjectForKey:key];
[[NSFileManager defaultManager] removeItemAtPath:[self cachePathForKey:key] error:nil];
}
- (void)clearMemory
{
[cacheInQueue cancelAllOperations]; // won't be able to complete
[memCache removeAllObjects];
}
- (void)clearDisk
{
[cacheInQueue cancelAllOperations];
[[NSFileManager defaultManager] removeItemAtPath:diskCachePath error:nil];
[[NSFileManager defaultManager] createDirectoryAtPath:diskCachePath
withIntermediateDirectories:YES
attributes:nil
error:NULL];
}
- (void)cleanDisk
{
NSDate *expirationDate = [NSDate dateWithTimeIntervalSinceNow:-cacheMaxCacheAge];
NSDirectoryEnumerator *fileEnumerator = [[NSFileManager defaultManager] enumeratorAtPath:diskCachePath];
for (NSString *fileName in fileEnumerator)
{
NSString *filePath = [diskCachePath stringByAppendingPathComponent:fileName];
NSDictionary *attrs = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];
if ([[[attrs fileModificationDate] laterDate:expirationDate] isEqualToDate:expirationDate])
{
[[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
}
}
}
@end