iOS协议

ios中的协议:大家猛一看 感觉挺高深的  其实ios中的协议就是c#,java中的接口 只是变了一个形式;

自我感觉ios中的协议没有c#中的接口好  人家的接口就是固定你的程序内容的  而ios中的协议和类就有点冲突了

下面写一协议  请看下面的程序

先生名个propcle的协议  在声明个pro的类继承这个协议 然后通过主函数调用

#import <Foundation/Foundation.h>

 

@protocol Prorocol <NSObject>

 

@required      //它下面定义必须要的函数  就是说pro类中必须实现的函数 如果步实现 编译器就会报错的  

-(void)print;

 

@optional  //他下面定义可有的  就算pro类中不实现这个函数也不会报错

-(void)print2;  

 

@end

 

 

@interface Pro : NSObject<Prorocol>

 

@end

@implementation Pro

 

-(void)print

{

    NSLog(@"我是必须的");

}

-(void)print2

{

    NSLog(@"我是可有的");

}

@end

 

 

 

 

 

 

int main(int argc, const char * argv[])

{

 

    @autoreleasepool {

        

        // insert code here...

        Pro *p=[[Pro alloc] init];

        [p print2];

        [p print];

        NSLog(@"Hello, World!");

        

    }

    return 0;

}

 运行结果:
 
如果我们把上面类中的print函数删除  编译器就会给我们报错
 
 
原文地址:https://www.cnblogs.com/flyingdreaming/p/prorocol.html