1.定义一个MyClass类,和一个TestShow协议:
@protocol TestShow;
@interface MyClass : NSObject<NSCopying>//遵守NSCopying协议
{
id<TestShow> delegate;
}
@property (nonatomic,retain) id<TestShow> delegate;
@end
//自定义代理
@protocol TestShow
-(void)show;
@end
2.MyClass类的实现:
@implementation MyClass
@synthesize delegate;
//overwrite init method
-(id)init
{
NSLog(@"Init called!");
return [super init];
}
// NSCopying delegate's implementation
-(id)copyWithZone:(NSZone*)zone
{
MyClass *copy=[[ [self class] allocWithZone:zone] init];
return copy;
}
@end
3.测试:
1.在测试类中遵守TestShow协议,并实现方法:
-(void)show
{
NSLog(@"In MainViewController");
}
2.测试代码如下:
MyClass * test1=[[MyClass alloc] init];
MyClass * test2=[MyClass new];
MyClass * test3=[test1 copy];
test3.delegate=self;
[test3.delegate show];
NSLog(@"test1's:%d",[test1 retainCount]);
NSLog(@"test2's:%d",[test2 retainCount]);
[test1 release];
[test2 release];
[test3 release];