Last active
September 26, 2015 19:47
-
-
Save onmyway133/50d7139314bc196bf2e2 to your computer and use it in GitHub Desktop.
SimpleCache.m
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
// CacheItem.h | |
@interface CacheItem : RLMObject | |
@property NSString *key; | |
@property NSData *value; | |
@end | |
// CacheItem.m | |
@implementation CacheItem | |
+ (NSString *)primaryKey { | |
return @"key"; | |
} | |
@end | |
// SimpleCache.h | |
@interface SimpleCache : NSObject | |
+ (instancetype)sharedCache; | |
- (CacheItem *)objectForKey:(NSString *)key; | |
- (void)saveObject:(CacheItem *)item; | |
- (void)clear | |
@end | |
// SimpleCache.m | |
@interface SimpleCache () | |
@property (nonatomic, strong) RLMRealm *defaultRealm; | |
@property (nonatomic, strong) NSCache *memCache; | |
@end | |
@implementation SimpleCache | |
+ (instancetype)sharedCache { | |
static sharedCache *instance = nil; | |
static dispatch_once_t onceToken; | |
dispatch_once(&onceToken, ^{ | |
instance = [[self alloc] init]; | |
}); | |
return instance; | |
} | |
- (instancetype)init { | |
self = [super init]; | |
if (self) { | |
_defaultRealm = [RLMRealm defaultRealm]; | |
_memCache = [[NSCache alloc] init]; | |
} | |
return self; | |
} | |
#pragma mark - Persistence | |
- (CacheItem *)objectForKey:(NSString *)key { | |
CacheItem *item = [self.memCache objectForKey:key]; | |
if (!item) { | |
item = [CacheItem objectForPrimaryKey:key]; | |
if (item) { | |
[self.memCache setObject:item forKey:key]; | |
} | |
} | |
return item; | |
} | |
- (void)saveObject:(CacheItem *)item { | |
if (!item.key || !item.value) { | |
return; | |
} | |
[self.defaultRealm transactionWithBlock:^{ | |
[self.defaultRealm addOrUpdateObject:item]; | |
}]; | |
// Save to mem cache after the object is saved to Realm | |
[self.memCache setObject:item forKey:item.key]; | |
} | |
#pragma mark - Clear | |
- (void)clear { | |
[self.memCache removeAllObjects]; | |
[self.defaultRealm transactionWithBlock:^{ | |
[self.defaultRealm deleteObjects:[CacheItem allObjects]]; | |
}]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment