Permalink
Browse files

Persist images to the file system for items

  • Loading branch information...
1 parent 2068bb7 commit 8da3f4150a603d21378863b1f96f8a6ef898db14 Ryan Blunden committed Jan 16, 2013
Showing with 51 additions and 6 deletions.
  1. +46 −1 Homepwner/Homepwner/BNRImageStore.m
  2. +0 −2 Homepwner/Homepwner/BNRItem.h
  3. +5 −3 Homepwner/Homepwner/BNRItemStore.m
@@ -11,6 +11,8 @@ @interface BNRImageStore () {
NSMutableDictionary *_dictionary;
}
+- (NSString *)imagePathForKey:(NSString *)key;
+
@end
@implementation BNRImageStore
@@ -40,13 +42,56 @@ - (id)init {
- (void)setImage:(UIImage *)i forKey:(NSString *)key {
[_dictionary setObject:i forKey:key];
+
+ // Create full path for image
+ NSString *imagePath = [self imagePathForKey:key];
+
+ // Turn image into JPEG data
+ NSData *d = UIImageJPEGRepresentation(i, 0.8);
+
+ // Write it to full path
+ [d writeToFile:imagePath atomically:YES];
+
}
- (UIImage *)imageForKey:(NSString *)key {
- return [_dictionary objectForKey:key];
+
+ // If possible, get it from the dictionary
+ UIImage *result = [_dictionary objectForKey:key];
+
+ if (!result) {
+ // Create UIImage object fro file
+ result = [UIImage imageWithContentsOfFile:[self imagePathForKey:key]];
+
+ // If we found an image on the file system, place it into the cache
+ if (result) {
+ [_dictionary setObject:result forKey:key];
+ }
+ else {
+ NSLog(@"Error: unable to find %@", [self imageForKey:key]);
+ }
+ }
+
+ return result;
}
- (void)removeImageForKey:(NSString *)key {
+ if (!key) {
+ return;
+ }
+
[_dictionary removeObjectForKey:key];
+
+ NSString *path = [self imagePathForKey:key];
+ [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
}
+
+- (NSString *)imagePathForKey:(NSString *)key {
+ NSArray *documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
+
+ NSString *documentdirectory = [documentDirectories objectAtIndex:0];
+
+ return [documentdirectory stringByAppendingPathComponent:key];
+}
+
@end
@@ -9,8 +9,6 @@
#import <Foundation/Foundation.h>
@interface BNRItem : NSObject <NSCoding>
-{
-}
@property (nonatomic, strong) BNRItem *containedItem;
@property (nonatomic, weak) BNRItem *container;
@@ -7,6 +7,7 @@
#import "BNRItemStore.h"
#import "BNRItem.h"
+#import "BNRImageStore.h"
@interface BNRItemStore () {
NSMutableArray *_allItems;
@@ -46,14 +47,15 @@ - (id)init {
}
- (BNRItem *)createItem {
- BNRItem *p = [BNRItem randomItem];
-
+ BNRItem *p = [[BNRItem alloc] init];
[_allItems addObject:p];
-
return p;
}
- (void)removeItem:(BNRItem *)item {
+ NSString *key = [item imageKey];
+ [[BNRImageStore sharedStore] removeImageForKey:key];
+
// We don't use "removeObject" here as that the message "isEqual" is sent to each object which the object can override
// Using removeObjectIdenticalTo ensures we're removing the same object passed in
[_allItems removeObjectIdenticalTo:item];

0 comments on commit 8da3f41

Please sign in to comment.