NSCopying协议在NSObject.h头文件中定义:
@protocol NSCopying
- (id)copyWithZone:(NSZone *)zone;
@end
实现copyWithZone:代理方法后,可以对对象使用copy方法。常见的NSString、NSArray、NSDictionary以及它们的mutable类型的对象都能使用copy方法。对无法使用copy方法的对象,我们可以通过类实现NSCopying协议,达到对象使用copy方法的目的。通常情况下,UIView对象无法使用copy方法,现在我通过UIView实现NSCopying协议的方式,让UIView的对象也能使用copy方法。
首先,写一个简单的UIView的类来实现NSCopying协议:
CopyView.h文件
#import <UIKit/UIKit.h>
@interface CopyView :UIView<NSCopying>
@end
#import "CopyView.h"
@implementation CopyView
- (id)initWithFrame:(CGRect)frame
{
self = [superinitWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
//实现delegate方法
- (id)copyWithZone:(NSZone *)zone
{
CopyView *copy = [[[selfclass] allocWithZone:zone]init];
return copy;
}
@end
现在我们来测试使用一下CopyView类,由于是测试,代码写的比较简单。直接在controlView的viewDidLoad中使用该类。
- (void)viewDidLoad
{
[self.viewsetBackgroundColor:[UIColorwhiteColor]];
[superviewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
CopyView * cp1 = [[CopyViewalloc] initWithFrame:CGRectMake(10,10, 300, 100)];
cp1.backgroundColor = [UIColorblackColor];
[self.viewaddSubview:cp1];
CopyView * cp2 = nil;
cp2 = [cp1copy];
cp2.frame =CGRectMake(10,10, 300, 100);
cp2.backgroundColor = [UIColorredColor];
NSLog(@"cp1:%@",cp1);
NSLog(@"cp2:%@",cp2);
cp2.center = self.view.center;
[self.viewaddSubview:cp2];
[cp1release];
}
运行后的结果如下:
控制台输出如下:
2013-04-22 10:57:04.440 Copy协议[755:c07] cp1:<CopyView: 0x7575dc0; frame = (10 10; 300 100); layer = <CALayer: 0x7575660>>
2013-04-22 10:57:04.442 Copy协议[755:c07] cp2:<CopyView: 0x7576260; frame = (10 10; 300 100); layer = <CALayer: 0x75762c0>>
结论:
cp1与cp2内存地址不一样,从运行后的模拟器截图也可以很清楚的看出,copy方法完成了对cp1的深拷贝。