Graphics Programs Reference
In-Depth Information
Writing to the Filesystem with NSData
Our archiving in
Homepwner
saves and loads the
imageKey
for each
BNRItem
, but what
about the images themselves? Let's extend the image store to save images as they are ad-
ded and fetch them as they are needed.
The images for
BNRItem
instances are created by user interaction and are only stored
within the application. Therefore, the
Documents
directory is the best place to store them.
You can use the image key generated when the user takes a picture to name the image in
the filesystem.
Open
BNRImageStore.h
and add a new method declaration.
- (NSString *)imagePathForKey:(NSString *)key;
Implement
imagePathForKey:
in
BNRImageStore.m
to create a path in the docu-
ments directory using a given key.
- (NSString *)imagePathForKey:(NSString *)key
{
NSArray *documentDirectories =
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask,
YES);
NSString *documentDirectory = [documentDirectories objectAtIndex:0];
return [documentDirectory stringByAppendingPathComponent:key];
}
To save and load an image, you are going to copy the JPEG representation of the image in-
to a buffer in memory. Instead of just malloc'ing a buffer, Objective-C programmers have a
handy class to create, maintain, and destroy these sorts of buffers -
NSData
. An
NSData
instance holds some number of bytes of binary data, and you will use
NSData
store image
data.
In
BNRImageStore.m
, modify
setImage:forKey:
to get a path and save the image.
- (void)setImage:(UIImage *)i forKey:(NSString *)s
{
[dictionary setObject:i forKey:s];
// Create full path for image
NSString *imagePath = [self imagePathForKey:s];
// Turn image into JPEG data,
NSData *d = UIImageJPEGRepresentation(i, 0.5);
// Write it to full path