Created
October 16, 2014 16:54
-
-
Save cloudwalking/66990a244b249c57f443 to your computer and use it in GitHub Desktop.
Cache
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <CommonCrypto/CommonDigest.h> | |
#import "Cache.h" | |
@implementation Cache | |
+ (void)cacheObject:(id)object forKey:(NSString *)key { | |
NSString *path = [self pathForKey:key]; | |
[NSKeyedArchiver archiveRootObject:object toFile:path]; | |
} | |
+ (id)objectForCacheKey:(NSString *)key { | |
NSString *path = [self pathForKey:key]; | |
if ([[NSFileManager defaultManager] fileExistsAtPath:path]) { | |
return [NSKeyedUnarchiver unarchiveObjectWithFile:path]; | |
} else { | |
return nil; | |
} | |
} | |
+ (NSString *)MD5:(NSString *)str { | |
const char *ptr = [str UTF8String]; | |
unsigned char md5Buffer[CC_MD5_DIGEST_LENGTH]; | |
CC_MD5(ptr, strlen(ptr), md5Buffer); | |
NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2]; | |
for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) { | |
[output appendFormat:@"%02x", md5Buffer[i]]; | |
} | |
return output; | |
} | |
+ (NSString *)pathForKey:(NSString *)key { | |
NSString *hash = [self MD5:key]; | |
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]; | |
NSString *topicDirectory = [documentsPath stringByAppendingPathComponent:@"cache"]; | |
if (![[NSFileManager defaultManager] fileExistsAtPath:topicDirectory]) { | |
[[NSFileManager defaultManager] createDirectoryAtPath:topicDirectory | |
withIntermediateDirectories:NO | |
attributes:nil | |
error:nil]; | |
} | |
NSString *path = [topicDirectory stringByAppendingPathComponent:hash]; | |
return path; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment