UIImageViewオブジェクトのディープコピーを作成するには、NSKeyedArchiverを使用してアーカイブし、NSKeyedUnarchiverを使用してアーカイブを解除する必要がありますが、UIImageはNSCodingプロトコルに準拠していないため、このアプローチには問題があります。最初に行う必要があるのは、NSCodingをサポートするようにUIImageクラスを拡張することです。
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
DeepCopy
次に、UIImageViewと次のコードに(たとえば)名前の新しいカテゴリを追加します。
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];