Permalink
Browse files

Disk-write operations can be a performance bottleneck so should be pe…

…rformed

asynchronously if possible.
  • Loading branch information...
1 parent 2bea9c3 commit dc7f945bf69090db0db18d762e996457e652edef Luke Redpath committed Nov 1, 2009
Showing with 20 additions and 1 deletion.
  1. +1 −0 EGOCache.h
  2. +19 −1 EGOCache.m
View
@@ -16,6 +16,7 @@
@interface EGOCache : NSObject {
@private
NSMutableDictionary* cacheDictionary;
+ NSOperationQueue* diskOperationQueue;
}
+ (EGOCache*)currentCache;
View
@@ -55,6 +55,8 @@ - (id)init {
cacheDictionary = [[NSMutableDictionary alloc] init];
}
+ diskOperationQueue = [[NSOperationQueue alloc] init];
+
[[NSFileManager defaultManager] createDirectoryAtPath:EGOCacheDirectory()
withIntermediateDirectories:YES
attributes:nil
@@ -96,7 +98,17 @@ - (void)setData:(NSData*)data forKey:(NSString*)key {
}
- (void)setData:(NSData*)data forKey:(NSString*)key withTimeoutInterval:(NSTimeInterval)timeoutInterval {
- [data writeToFile:cachePathForKey(key) atomically:YES];
+ NSString *cachePath = cachePathForKey(key);
+ NSInvocation *diskWriteInvocation = [NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(writeData:toPath:)]];
+ [diskWriteInvocation setTarget:self];
+ [diskWriteInvocation setSelector:@selector(writeData:toPath:)];
+ [diskWriteInvocation setArgument:&data atIndex:2];
+ [diskWriteInvocation setArgument:&cachePath atIndex:3];
+
+ NSInvocationOperation *diskWriteOperation = [[NSInvocationOperation alloc] initWithInvocation:diskWriteInvocation];
+ [diskOperationQueue addOperation:diskWriteOperation];
+ [diskWriteOperation release];
+
[cacheDictionary setObject:[NSDate dateWithTimeIntervalSinceNow:timeoutInterval] forKey:key];
[[NSUserDefaults standardUserDefaults] setObject:cacheDictionary forKey:@"EGOCache"];
@@ -113,6 +125,11 @@ - (NSData*)dataForKey:(NSString*)key {
}
}
+- (void)writeData:(NSData*)data toPath:(NSString *)path;
+{
+ [data writeToFile:path atomically:YES];
+}
+
- (void)saveCacheDictionary {
[[NSUserDefaults standardUserDefaults] synchronize];
}
@@ -170,6 +187,7 @@ - (void)setImage:(NSImage*)anImage forKey:(NSString*)key withTimeoutInterval:(NS
#pragma mark -
- (void)dealloc {
+ [diskOperationQueue release];
[cacheDictionary release];
[super dealloc];
}

0 comments on commit dc7f945

Please sign in to comment.