Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

iphone - Storing image in plist

How can we store images in plist file. Where is this plist file stored? Can anyone give me an example? Answers will be greatly appreciated!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...