gpt4 book ai didi

iphone - UIKit中的类如何实现深拷贝?

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:04:26 25 4
gpt4 key购买 nike

我有一个对象 imageView1。我想创建另一个对象来保留 imageView1 的深拷贝。像这样,

UIImageView *imageView1 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"background.png"]];
UIImageView *imageView2 = [imageView1 copy];

我知道它不起作用,因为 UIImageView 不符合 NSCopying。但应该如何 我愿意吗?

最佳答案

要创建 UIImageView 对象的深拷贝,您需要使用 NSKeyedArchiver 将其归档,然后使用 NSKeyedUnarchiver 将其取消归档,但这种方法存在一个问题,因为 UIImage 不符合 NSCoding 协议(protocol)。您首先需要做的是扩展 UIImage 类以支持 NSCoding。

UIImage 上添加一个名称为 NSCoding 的新类别,并放置以下代码:

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];

关于iphone - UIKit中的类如何实现深拷贝?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10188387/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com