Objective-C 语法五(协议)
来源:互联网 发布:html如何连接数据库 编辑:程序博客网 时间:2024/05/29 18:13
Objective-C 语法五(协议)
首先申明下,本文为笔者学习《Objective-C 基础教程》的笔记,并加入笔者自己的理解和归纳总结。
协议是包含了方法和属性的有名称列表。
1、创建协议
@protocol关键字声明了一个协议。@protocol KeyListener- (void) onKeyDown;- (void) onKeyUp;@end
2、协议可以继承父协议。
@protocol MouseListener <KeyListener>- (void) onKeyMove;@end
3、协议中的关键字
@required:表示必须强制实现的方法@optional:表示可以有选择性的实现方法
4、实现协议
NSCopying协议是对对象进行拷贝的协议。Shape实现协议NSCopying,实现方法copyWithZone。Rectangle继承了Shape,同样实现方法copyWithZone。
@interface Shape : NSObject <NSCopying>@property int width;@property int height;@end@implementation Shape @synthesize width;@synthesize height;- (id) init {if (self = [super init]) {width = 20;height = 20;NSLog(@"Shape init");}return self;}- (id) copyWithZone: (NSZone *)zone {Shape* shapeCopy = [[[self class]allocWithZone:zone] init];shapeCopy.width = width;shapeCopy.height = height;return shapeCopy;}- (NSString*) description {return [NSString stringWithFormat: @"(%d, %d)",[self width], [self height]];}@end@interface Rectangle : Shape@property int radius;@end@implementation Rectangle @synthesize radius;- (id) copyWithZone: (NSZone *)zone {Rectangle* rectangleCopy = [super copyWithZone: zone];rectangleCopy.radius = [self radius];return rectangleCopy;}- (NSString*) description {return [NSString stringWithFormat: @"(%d, %d) radius = %d",[self width], [self height], [self radius]];}@endint main(int argc, const char* argv[]) {@autoreleasepool {Shape* shape = [[Shape alloc] init];shape.width = 30;shape.height = 20;NSLog(@"%@", [shape copy]);Rectangle* rect = [[Rectangle alloc] init];rect.width = 100;rect.height = 60;rect.radius = 5;NSLog(@"%@", [rect copy]);}return 0;}
阅读全文
0 0
- Objective-C 语法五(协议)
- LHF Objective-C语法(8)协议
- Objective-C 协议(protocol)
- Objective-C 协议(protocol)
- Objective-C 协议(protocol)
- Objective-C 协议(protocol)
- Objective-C 协议(protocol)
- Objective-C 协议(protocol)
- 黑马程序员-iOS基础-Objective-C基础(五)核心语法(下)
- Objective-C语法之Object对象的那些事儿(五)
- Objective-C语法之Object对象的那些事儿(五)
- Objective-C语法之Object对象的那些事儿(五)
- objective-c基础语法学习之--(5):类目,延展,协议,代理
- iOS学习笔记56(Runtime)-Objective-C Runtime 运行时之五:协议与分类
- Objective-C Runtime 运行时之五:协议与分类
- Objective-C Runtime 运行时之五:协议与分类
- Objective-C Runtime 运行时之五:协议与分类
- Objective-C Runtime 运行时之五:协议与分类
- 过滤器和拦截器的区别
- 线性模型
- Tomcat历史版本下载
- HTML canvas 绘制
- 移植SDL到JZ2440显示BMP图片
- Objective-C 语法五(协议)
- golang if-else 和 switch-fallthrough 比较
- 实习背后的选择——早知道还是比较好
- 面向接口编程详解(一)——思想基础(转)
- RecyclerView源码分析
- 光耦的作用及工作原理
- 献给那些浮躁的年轻人
- ssm框架之登录验证
- Android 支持多种屏幕第一篇