Last active
August 29, 2015 14:02
-
-
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.
This file contains 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
// | |
// 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 |
This file contains 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
// | |
// 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