OC協議protocol

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;

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容