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;
}