开发者

Storing image in plist

开发者 https://www.devze.com 2022-12-24 03:40 出处:网络
How can we store ima开发者_如何学Goges in plist file. Where is this plist file stored? Can anyone give me an example? Answers will be greatly appreciated!The UIImage doesn\'t implement the NSCoder pro

How can we store ima开发者_如何学Goges in plist file. Where is this plist file stored? Can anyone give me an example? Answers will be greatly appreciated!


The UIImage doesn't implement the NSCoder protocol directly that is necessary for storage in plists.

But, it is fairly easy to add like below.

UIImage+NSCoder.h

#import <Foundation/Foundation.h>

@interface UIImage (MyExtensions)
- (void)encodeWithCoder:(NSCoder *)encoder;
- (id)initWithCoder:(NSCoder *)decoder;
@end

UIImage+NSCoder.m

#import "UIImage+NSCoder.h"

@implementation UIImage (MyExtensions)

- (void)encodeWithCoder:(NSCoder *)encoder
{
  [encoder encodeDataObject:UIImagePNGRepresentation(self)];
}

- (id)initWithCoder:(NSCoder *)decoder
{
  return [self initWithData:[decoder decodeDataObject]];
}

@end

When this has been added you will be able to store UIImages in plist with ie

// Get a full path to a plist within the Documents folder for the app
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                     NSUserDomainMask,
                                                     YES);
NSString *path = [NSString stringWithFormat:@"%@/my.plist",
                                              [paths objectAtIndex:0]];

// Place an image in a dictionary that will be stored as a plist
[dictionary setObject:image forKey:@"image"];

// Write the dictionary to the filesystem as a plist
[NSKeyedArchiver archiveRootObject:dictionary toFile:path];

Note: I do not recommend doing this, unless you really want to, ie for really small images.


Always store the image path in the .plist, never the actual image. If you do, you'll take a performance hit. You want to load images as you need them, not all at once.


Depends on where and when these images are known to the application.

For images as part of the application bundler, here may provide some insight. If you want to store images during the running of the application you can use the same concepts (user plist with relative paths to images).

-- Frank


plist files are meant to store key-value pairs, not the resources of your application. The icons, images and forms are usually stored in a .xib file (see Interface Builder)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号