Objective-c - 协议(protocol)的使用
来源:互联网 发布:mac wine怎么用 编辑:程序博客网 时间:2024/05/17 11:59
/*
Objective-c - 协议的使用
协议:protocol.
类可以遵守协议,遵守协议的类就拥有了该协议中的所有方法的声明,而不用自己声明.
协议是专门用来写方法的声明的,协议中不能写属性.
协议中也可以写@property,但是协议中的@property只会生成setter/getter方法的声明.
如果一个类想要拥有某个协议中的所有的方法的声明,那么这个类只需要遵守这个协议就可以了.
遵守协议的格式:
@interface 类名 : 父类名 <协议名称>
@end
继承具有单根性,协议可以多遵守,一个类可以遵守多个协议格式如下:
@interface 类名 : 父类名 <协议名称,协议名称,......>
@end
注意:
一个类遵守了一个协议,类只是拥有了协议中的方法的声明,还需要自己去写方法上的实现;
如果一个类遵守了协议,但是没有实现协议中的方法,编译器在编译的时候不会报错,但是会警告,在执行的时候,如果调用这个协议的方法,而这个协议中的方法在类中并没有实现,就会运行报错.
代码如下:
*/
#import <Foundation/Foundation.h>
#pragma mark -
#pragma mark #import "YYProtocol.h"
@protocol YYProtocol <NSObject>
- (void)sayHi;
@end
#pragma mark -
#pragma mark #import "YYPerson.h"
//类的声明,YYPerson类遵守了协议,所以拥有了协议中的sayHi的方法的声明,自己实现就可以了
@interface YYPerson : NSObject <YYProtocol>
//自定义构造方法
- (instancetype)initWithName:(NSString *)name;
+ (instancetype)personWithName:(NSString *)name;
@end
//延展,私有化属性@property写在了延展中
@interface YYPerson ()
@property(nonatomic,strong)NSString *name;
@end
//类的实现
@implementation YYPerson
- (void)sayHi
{
NSLog(@"大家好!我叫%@!",self.name);
}
//自定义构造方法
- (instancetype)initWithName:(NSString *)name
{
if(self = [superinit])
{
self.name = name;
}
return self;
}
+ (instancetype)personWithName:(NSString *)name
{
return [[selfalloc]initWithName:name];
}
@end
#pragma mark -
#pragma mark main函数
int main(int argc,constchar * argv[]) {
//创建对象
YYPerson *xiaoming = [YYPersonpersonWithName:@"小明"];
//调用方法
[xiaoming sayHi];
return 0;
}
- Objective-C 【protocol-协议 的了解使用】
- Objective-c - 协议(protocol)的使用
- Objective-c的协议protocol
- Objective-c 协议(protocol)
- Objective C 协议(Protocol)
- Objective-C 协议 protocol
- objective-c中协议protocol的理解
- Objective-C中的协议Protocol
- Objective-C 协议(protocol)
- Objective-C之protocol协议
- Objective-C 协议(protocol)
- Objective-C 协议(protocol)
- Objective-C 协议(protocol)
- Objective-C 协议(protocol)
- Objective-C 协议(protocol)
- Objective-C 13 协议protocol
- objective-c中关于协议protocol的一些理解
- 【Objective-C】OC中协议(Protocol)的基本概念和用法
- 以先序字符串方式建立二叉树
- JS 如何改变span标签的是否隐藏属性
- 远程连接MYSQL提示 Host *** is not allowed to connect to this MySQL server
- libpng库编码图片为png(RGB压缩为png图片:与ffmpeg视频解码存储为png图片)
- java包和类命名规范
- Objective-c - 协议(protocol)的使用
- Android DownloadManager 的使用
- Virtualbox搭建局域网设置,安装ambari hadoop集群管理第一步
- 问题六十二:怎么求一元十次方程在区间内的所有不相等的实根
- Ubuntu 16.04安装Chrome浏览器
- 0x5f3759df这个快速开方中的常数的数学依据和原理
- echarts3 使用((绘制各种图表,地图))
- ssm框架的定时任务
- python爬虫-百度百科词条