Graphics Programs Reference
In-Depth Information
view of the view controller that presented it is not. In our case, the low-memory warning
destroys
DetailViewController
's
view
, and the
imageView
is no longer avail-
able when we try to set it.
To get around this problem, we must create a separate store for images. Instead of putting
the image directly into the
imageView
, we will put it into this store. Then when the
De-
tailViewController
's view next appears on screen, we'll have the
De-
tailViewController
grab the image from the image store and put it into its own
imageView
. In general, this is a best practice: a view controller should re-populate its
view
's subviews with data whenever it is sent the message
viewWillAppear:
to
eliminate the possibility that a low-memory warning could wipe out its content.
Creating BNRImageStore
The image store will hold all the pictures the user will take. In
Chapter 14
,
you will have
the
BNRItem
objects write out their instance variables to a file, which will then be read
in when the application starts. However, as we've seen, images tend to be very large, so
it's a good idea to keep them separate from other data. The image store will fetch and
cache the images as they are needed. It will also be able to flush the cache if the device
runs low on memory. Create a new
NSObject
subclass called
BNRImageStore
. Open
BNRImageStore.h
and create its interface:
#import <UIKit/UIKit.h>
@interface BNRImageStore : NSObject
{
NSMutableDictionary *dictionary;
}
+ (BNRImageStore *)sharedStore;
- (void)setImage:(UIImage *)i forKey:(NSString *)s;
- (UIImage *)imageForKey:(NSString *)s;
- (void)deleteImageForKey:(NSString *)s;
@end
Like the
BNRItemStore
, the
BNRImageStore
needs to be a singleton. In
BNRImageStore.m
, write the following code to ensure
BNRImageStore
's singleton
status.
@implementation BNRImageStore
+ (id)allocWithZone:(NSZone *)zone
{
return [self sharedStore];
}