0
@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 文件中。我应该如何更改代码以仅保存图像路径\名称而不是保存实际图片。

4

2 回答 2

0

你应该使用

@property (copy) NSString *thumbImage;

并仅保存图像名称而不是

@property (strong) UIImage *thumbImage;

然后编码/编码为字符串。当您需要图像时,只需编写

[UIImage imageNamed:album1.thumbImage];

另一种解决方案是继承UIImage类,添加图片路径属性,重写UIImage的初始化方法以支持保存路径,重写coder/encoder方法

编辑:

这是一些示例代码:

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;
}
于 2012-12-14T16:29:07.580 回答
0

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

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

正如 rmaddy 所说,您无法从 UIImage 中获取它,因此您可能必须在创建图像时获取它并坚持使用它。

于 2012-12-14T16:19:23.653 回答