要创建UIImageView对象的深层副本,需要使用NSKeyedArchiver将其归档,然后使用NSKeyedUnarchiver将其解压缩,但由于UIImage不符合NSCoding协议,因此存在此方法的问题。你首先需要做的是扩展UIImage类来支持NSCoding。
与名NSCoding
上UIImage
添加一个新的类别,并把下面的代码:
的UIImage + NSCoder.h
#import <UIKit/UIKit.h>
@interface UIImage (NSCoding)
- (id)initWithCoder:(NSCoder *)decoder;
- (void)encodeWithCoder:(NSCoder *)encoder;
@end
的UIImage + NSCoder.m
#import "UIImage+NSCoder.h"
@implementation UIImage (NSCoding)
- (id)initWithCoder:(NSCoder *)decoder {
NSData *pngData = [decoder decodeObjectForKey:@"PNGRepresentation"];
[self autorelease];
self = [[UIImage alloc] initWithData:pngData];
return self;
}
- (void)encodeWithCoder:(NSCoder *)encoder {
[encoder encodeObject:UIImagePNGRepresentation(self) forKey:@"PNGRepresentation"];
}
@end
然后添加一个名称为的新类别
的UIImageView + DeepCopy.h
#import <UIKit/UIKit.h>
@interface UIImageView (DeepCopy)
-(UIImageView *)deepCopy;
@end
的UIImageView + DeepCopy.m
#import "UIImageView+DeepCopy.h"
#import "UIImage+NSCoder.h"
@implementation UIImageView (DeepCopy)
-(UIImageView *)deepCopy
{
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:self forKey:@"imageViewDeepCopy"];
[archiver finishEncoding];
[archiver release];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
UIImageView *imgView = [unarchiver decodeObjectForKey:@"imageViewDeepCopy"];
[unarchiver release];
[data release];
return imgView;
}
@end
用法:上的UIImageView和下面的代码(为前。) 导入您的UIImageView + DeepCopy.h
UIImageView *imgView1 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"picture.jpg"]];
UIImageView *imageView2 = [imgView1 deepCopy];
在任何体系结构中复制UI组件并不是一个好主意。 – Sulthan 2012-04-17 10:55:10
@Sulthan我明白你的意思。但是,我真的需要UIImageView来保存一些关于模型的数据。当然,它可以存储CGRect,fileName等。我认为这比直接使用UIImageView要复杂。感谢您的经验。我会照顾这个。 – tzzzoz 2012-04-17 11:55:58
你应该能够从你的模型创建UI,而不是让你的模型成为UI的一部分。 – Sulthan 2012-04-17 12:29:23