-
Notifications
You must be signed in to change notification settings - Fork 8
/
NSData+SDDataCache.m
executable file
·69 lines (60 loc) · 2.16 KB
/
NSData+SDDataCache.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
//
// NSData+SDDataCache.m
// SDCycleScrollView
//
// Created by aier on 15-3-30.
// Copyright (c) 2015年 GSD. All rights reserved.
//
#import "NSData+SDDataCache.h"
#import <CommonCrypto/CommonDigest.h>
#define kSDMaxCacheFileAmount 100
@implementation NSData (SDDataCache)
+ (NSString *)cachePath
{
NSString *path = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
path = [path stringByAppendingPathComponent:@"Caches"];
path = [path stringByAppendingPathComponent:@"SDDataCache"];
if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
[[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
}
return path;
}
+ (NSString *)creatMD5StringWithString:(NSString *)string
{
const char *original_str = [string UTF8String];
unsigned char result[CC_MD5_DIGEST_LENGTH];
CC_MD5(original_str, (CC_LONG)strlen(original_str), result);
NSMutableString *hash = [NSMutableString string];
for (int i = 0; i < 16; i++)
[hash appendFormat:@"%02X", result[i]];
[hash lowercaseString];
return hash;
}
+ (NSString *)creatDataPathWithString:(NSString *)string
{
NSString *path = [NSData cachePath];
path = [path stringByAppendingPathComponent:[self creatMD5StringWithString:string]];
return path;
}
- (void)saveDataCacheWithIdentifier:(NSString *)identifier
{
NSString *path = [NSData creatDataPathWithString:identifier];
[self writeToFile:path atomically:YES];
}
+ (NSData *)getDataCacheWithIdentifier:(NSString *)identifier
{
static BOOL isCheckedCacheDisk = NO;
if (!isCheckedCacheDisk) {
NSFileManager *manager = [NSFileManager defaultManager];
NSArray *contents = [manager contentsOfDirectoryAtPath:[self cachePath] error:nil];
if (contents.count >= kSDMaxCacheFileAmount) {
NSLog(@"%@", [self cachePath]);
[manager removeItemAtPath:[self cachePath] error:nil];
}
isCheckedCacheDisk = YES;
}
NSString *path = [self creatDataPathWithString:identifier];
NSData *data = [NSData dataWithContentsOfFile:path];
return data;
}
@end