在plist中存储图像

isa*_*thg 5 iphone objective-c

我们如何在plist文件中存储图像.这个plist文件存储在哪里?谁能举个例子?答案将不胜感激!

epa*_*tel 8

UIImage不直接实现NSCoder协议是必要的存储在Plist档案.

但是,如下所示添加相当容易.

的UIImage + NSCoder.h

#import <Foundation/Foundation.h>

@interface UIImage (MyExtensions)
- (void)encodeWithCoder:(NSCoder *)encoder;
- (id)initWithCoder:(NSCoder *)decoder;
@end
Run Code Online (Sandbox Code Playgroud)

的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
Run Code Online (Sandbox Code Playgroud)

添加完成后,您就可以将UIImages存储在plist中

// 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];
Run Code Online (Sandbox Code Playgroud)

注意:我不建议这样做,除非你真的想要,即对于非常小的图像.


W D*_*son 5

始终将图像路径存储在 .plist 中,而不是实际图像。如果你这样做,你会受到性能的影响。您希望根据需要加载图像,而不是一次加载。