要创建 UIImageView 对象的深层副本,您需要使用 NSKeyedArchiver 将其归档,然后使用 NSKeyedUnarchiver 将其取消归档,但这种方法存在问题,因为 UIImage 不符合 NSCoding 协议。您首先需要做的是扩展 UIImage 类以支持 NSCoding。
添加一个名称为NSCoding
on的新类别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
为(例如)的新类别:
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+DeepCopy.h
UIImageView *imgView1 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"picture.jpg"]];
UIImageView *imageView2 = [imgView1 deepCopy];