Skip to content

Instantly share code, notes, and snippets.

@bleeckerj
Last active August 29, 2015 14:02
Show Gist options
  • Save bleeckerj/587684a635c14cde04f5 to your computer and use it in GitHub Desktop.
Save bleeckerj/587684a635c14cde04f5 to your computer and use it in GitHub Desktop.
NSMutableDictionary that acts like a very stoopid simple timed cache and can optionally notify you when something is removed.
//
// NSMutableDictionary+JCBDictionaryTimedCache.h
//
//
// Created by Julian Bleecker on 6/8/14.
//
//
#import <Foundation/Foundation.h>
typedef void(^NotifyHandler)(id<NSCopying>aKey);
@interface NSMutableDictionary (JCBDictionaryTimedCache)
- (void)setObject:(id)anObject forKey:(id<NSCopying>)aKey removeAfter:(NSTimeInterval)timeInterval;
- (void)setObject:(id)anObject forKey:(id<NSCopying>)aKey removeAfter:(NSTimeInterval)timeInterval notifyOnRemoval:(NotifyHandler)notifyHandler;
@end
//
// NSMutableDictionary+JCBDictionaryTimedCache.m
//
//
// Created by Julian Bleecker on 6/8/14.
//
//
#import "NSMutableDictionary+JCBDictionaryTimedCache.h"
@implementation NSMutableDictionary (JCBDictionaryTimedCache)
- (void)setObject:(id)anObject forKey:(id<NSCopying>)aKey removeAfter:(NSTimeInterval)timeInterval
{
[self setObject:anObject forKey:aKey removeAfter:timeInterval notifyOnRemoval:nil];
}
- (void)setObject:(id)anObject forKey:(id<NSCopying>)aKey removeAfter:(NSTimeInterval)timeInterval notifyOnRemoval:(NotifyHandler)notifyHandler
{
NSAssert(timeInterval > 0, @"timeInterval must be greater than zero");
[self setObject:anObject forKey:aKey];
[self performBlock:^{
[self removeObjectForKey:aKey];
if(notifyHandler) {
notifyHandler(aKey);
}
} afterDelay:timeInterval];
}
// perform a block after a specified number of seconds
- (void)performBlock:(void(^)())block afterDelay:(NSTimeInterval)delay {
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), block);
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment