美文网首页
OC协议protocol

OC协议protocol

作者: 浅笑嫣然9611 | 来源:发表于2017-08-10 09:55 被阅读0次

Person.h

##import

//1.引入协议文件

#import"MotherProtocol.h"

//2.遵守协议本类名:父类名后<协议>

@interfacePerson :NSObject

@property(nonatomic,strong)NSString*name;

-(void)eat;

@end

Person.m

#import"Person.h"

@implementationPerson

-(void)eat{

NSLog(@"吃吃吃,就知道吃");

}

//遵循协议,就需要实现协议中的方法

-(void)buy{

NSLog(@"来自协议中的方法-----买买买,就知道买");

}

-(void)cook{

NSLog(@"来自协议中的方法-----cooking");

}

-(void)washClothes{

NSLog(@"来自协议中的方法-----好好洗衣服");

}

@end

MotherProtocol.h

#import

@protocolMotherProtocol

@required//这个关键字下的方法一旦遵循协议就必须实现(--默认---)

//协议部分,只能声明方法不能声明属性

-(void)buy;

-(void)cook;

@optional//这个关键字下的方法遵循协议可实现可不实现

-(void)washClothes;

@end

main.m

#import

#import"Person.h"

intmain(intargc,constchar* argv[]) {

@autoreleasepool{

Person*person = [[Personalloc]init];

person.name=@"哈哈";

NSLog(@"%@",person.name);

[personeat];

//谁实现方法,谁调用方法

[personbuy];

[personcook];

[personwashClothes];

}

return0;

}

相关文章

网友评论

      本文标题:OC协议protocol

      本文链接:https://www.haomeiwen.com/subject/lkncrxtx.html