Object-c 细节之协议

Posted on 2012-03-13 17:09  无忧consume  阅读(203)  评论(0编辑  收藏  举报
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];

Copyright © 2024 无忧consume
Powered by .NET 8.0 on Kubernetes