NSCoding,保存图像路径而不是实际图像

时间:2012-12-14 14:50:33

标签: objective-c ios

@property (strong) UIImage *thumbImage;

...

albumData *album1 = [[albumData alloc]initWithTitle:@"Eminem" style:@"123" thumbImage:[UIImage imageNamed:@"1.jpeg"]];

...

- (void)encodeWithCoder:(NSCoder *)coder {
    NSData *image = UIImagePNGRepresentation(_thumbImage);
    [coder encodeObject:(image) forKey:@"thumbImageData"];

}

- (id)initWithCoder:(NSCoder *)coder {
    NSData *imgData = [coder decodeObjectForKey:@"thumbImageData"];
    _thumbImage = [UIImage imageWithData:imgData ];
    return self;
}

现在我正在使用上面的代码将数据保存在plist文件中。我应该如何更改代码以便仅保存图像路径\名称,而不是保存实际图片。

2 个答案:

答案 0 :(得分:0)

如果您有文件名,则可以使用-[NSBundle pathForResource:ofType:]获取其路径,例如

[[NSBundle mainBundle] pathForResource:@"1" ofType:@"jpeg"];

正如rmaddy所说,你无法从UIImage获得这个,所以你可能必须得到它并在创建图像时坚持下去。

答案 1 :(得分:0)

你应该使用

@property (copy) NSString *thumbImage;

并仅保存图片名称而不是

@property (strong) UIImage *thumbImage;

然后编码/编码为字符串。当你需要一个图像时,只需写下

[UIImage imageNamed:album1.thumbImage];

另一个解决方案是子类UIImage类,添加图像路径属性,owerride UIImage的初始化方法以支持保存路径和覆盖编码器/编码器方法

修改

以下是一些示例代码:

UIImageWithPath.h

 #import <UIKit/UIKit.h>

@interface UIImageWithPath : UIImage{
    NSString* filepath;
}

@property(nonatomic, readonly) NSString* filepath;

-(id)initWithImageFilePath:(NSString*) path;
@end

UIImageWithPath.m

#import "UIImageWithPath.h"

@implementation UIImageWithPath
@synthesize filepath;

-(id)initWithImageFilePath:(NSString*) path{
    self = [super initWithContentsOfFile:path];
    if(self){
        [filepath release];
        filepath = [path copy];
    }

    return self;
}

-(void)dealloc{
    [filepath release];
    [super dealloc];
}
@end

使用样本:

- (void)viewDidLoad
{
    [super viewDidLoad];

    img = [[UIImageWithPath alloc] initWithImageFilePath:[[NSBundle mainBundle] pathForResource:@"pause" ofType:@"png"]];
    iv.image = img;
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    NSLog(@"image file path %@", img.filepath);
}

所以现在你的代码/编码方法应如下所示:

-(void)encodeWithCoder:(NSCoder *)coder {
    NSString *path = _thumbImage.filepath;
    [coder encodeObject:(path) forKey:@"thumbImageData"];

}

- (id)initWithCoder:(NSCoder *)coder {
    NSString *path = [coder decodeObjectForKey:@"thumbImageData"];
    _thumbImage = [[UIImageWithPath alloc] initWithImageFilePath:path];
    return self;
}