协议

协议:(有属性和方法, 只有.h文件)
是一种要求,规则
对应程序来讲,是只声明函数名,不实现
协议可以被继承,包括多个父协议,但是类只有一个父类,协议可以多重采纳,一个类可以一次采纳多个协议,用协议来实现多重继承

一个类遵守一个协议:.h文件加头文件,与<协议名>
@interface 类名 (分类类名): 父类名 <协议名>

实现协议中的声明方法
关键字:

@optinal (可选的) :声明可选遵守的属性和方法
@required (必须的) :声明必须遵守的属性和方法 默认关键字
针对属性:@synthesize (合成器) 如:synthesize name = _name;

使用形式:多态
a.函数参数多态
b.数组多态
c.返回值多态

协议多态形式:

//数组协议多态
void test5()
{
    id<TRProtocol2> b[2]; //b[i]只能调用协议中的方法,不能调用类中自定义的方法
    b[0] = [[TRClassA alloc] init];
    b[1] = [[TRClassB alloc] init];
    for (int i = 0; i < 2; i++)
    {
        [b[i] method1];
    }
}
//参数协议多态
void fun(id<TRProtocol2> a)
{
    [a method1];
}
void test6()
{
    TRClassA *objA = [[TRClassA alloc] init];
    fun(objA);
    TRClassB *objB = [[TRClassB alloc] init];
    fun(objB);
}
//返回值协议多态
typedef enum
{
    CLASSA, CLASSB, CLASSC,
}Type;
id<TRProtocol2> get(Type type)
{
    switch (type) {
        case CLASSA:
            return [[TRClassA alloc] init];
        case CLASSB:
            return [[TRClassB alloc] init];
        case CLASSC:
            return [[TRClassC alloc] init];
    }
}
void test7()
{
    [get(CLASSA) method0];
    [get(CLASSB) method0];
}

注:继承只支持单重继承与多层继承,而用协议来实现多重继承,协议可以多重采纳<Protocol1, Protocol2 >

成功的三大原则: 1、坚持 2、不要脸 3、坚持不要脸
原文地址:https://www.cnblogs.com/xulinmei/p/7413670.html