Skip to content

Commit

Permalink
Fixed a bunch of bugs that occured when I actually compiled those las…
Browse files Browse the repository at this point in the history
…t few commits. Fixed a bug that caused NSUserDefaults to save too many times too fast, causing slow downs in the app.
  • Loading branch information
shnhrrsn committed Oct 20, 2009
1 parent 83c6675 commit a54a6ae
Showing 1 changed file with 16 additions and 11 deletions.
27 changes: 16 additions & 11 deletions EGOCache.m
Original file line number Diff line number Diff line change
Expand Up @@ -11,21 +11,19 @@
static NSString* _EGOCacheDirectory;

static inline NSString* EGOCacheDirectory() {
@synchronized(self) {
if(!EGOCacheDirectory) {
#ifdef TARGET_OS_IPHONE
_EGOCacheDirectory = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/EGOCache"] retain];
#else
NSString* appSupportDir = [NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES) objectAtIndex:0];
_EGOCacheDirectory = [[[appSupportDir stringByAppendingPathComponent:[[NSProcessInfo processInfo] processName]] stringByAppendingPathComponent:@"EGOCache"] retain];
#endif
}
if(!_EGOCacheDirectory) {
#ifdef TARGET_OS_IPHONE
_EGOCacheDirectory = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/EGOCache"] retain];
#else
NSString* appSupportDir = [NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES) objectAtIndex:0];
_EGOCacheDirectory = [[[appSupportDir stringByAppendingPathComponent:[[NSProcessInfo processInfo] processName]] stringByAppendingPathComponent:@"EGOCache"] retain];
#endif
}

return _EGOCacheDirectory;
}

static inline NSString* cachePathForKey(key) {
static inline NSString* cachePathForKey(NSString* key) {
return [EGOCacheDirectory() stringByAppendingPathComponent:key];
}

Expand Down Expand Up @@ -87,7 +85,10 @@ - (void)setData:(NSData*)data forKey:(NSString*)key withTimeoutInterval:(NSTimeI
[data writeToFile:cachePathForKey(key) atomically:YES];
[cacheDictionary setObject:[NSDate dateWithTimeIntervalSinceNow:timeoutInterval] forKey:key];
[[NSUserDefaults standardUserDefaults] setObject:cacheDictionary forKey:@"EGOCache"];
[[NSUserDefaults standardUserDefaults] synchronize];

// Prevents multiple-rapid user defaults saves from happening, which will slow down your app
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(saveCacheDictionary) object:nil];
[self performSelector:@selector(saveCacheDictionary) withObject:nil afterDelay:1.0];
}

- (NSData*)dataForKey:(NSString*)key {
Expand All @@ -98,6 +99,10 @@ - (NSData*)dataForKey:(NSString*)key {
}
}

- (void)saveCacheDictionary {
[[NSUserDefaults standardUserDefaults] synchronize];
}

#pragma mark -
#pragma mark String methods

Expand Down

0 comments on commit a54a6ae

Please sign in to comment.