main.m
#import <Foundation/Foundation.h>
#import "Person.h"
#import "Wife.h"
#import "WifeCondition.h"
int main(int argc, const char * argv[]) {
Person *p = [Person new];
// 1.协议的第一个应用场景, 可以将协议写在数据类型的右边, 明确的标注如果想给该变量赋值, 那么该对象必须遵守某个协议
// Wife<WifeCondition> *w = [Wife new];
Wife *w = [Wife new];
p.wife = w;
[p show];
return 0;
}
WifeCondition.h
#import <Foundation/Foundation.h>
@protocol WifeCondition <NSObject>
// 会做饭
- (void)cooking;
// 会洗衣服
- (void)washing;
// 有一份好工作
- (void)job;
@end
Person.h
#import <Foundation/Foundation.h>
#import "Wife.h"
@interface Person : NSObject
// 媳妇
// 注意: 记住一点, 类型限定是写在数据类型的右边的
@property (nonatomic, strong) Wife<WifeCondition> *wife;
- (void)show;
@end
Person.m
#import "Person.h"
@implementation Person
- (void)show
{
// 注意(重要): 虽然在接受某一个对象的时候, 对这个对象进行了类型限定(限定它必须实现某个协议), 但是并不意味着这个对象就真正的实现了该方法. 所以每次在调用对象的协议方法时应该进行一次验证
if ([self.wife respondsToSelector:@selector(cooking)]) {
[self.wife cooking];
}
if ([self.wife respondsToSelector:@selector(washing)]) {
[self.wife washing];
}
if ([self.wife respondsToSelector:@selector(job)]) {
[self.wife job];
}
}
@end
Wife.h
#import <Foundation/Foundation.h>
#import "WifeCondition.h"
@interface Wife : NSObject <WifeCondition>
@end
Wife.m
#import "Wife.h"
@implementation Wife
// 会做饭
- (void)cooking
{
NSLog(@"%s", __func__);
}
// 会洗衣服
- (void)washing
{
NSLog(@"%s", __func__);
}
// 有一份好工作
- (void)job
{
NSLog(@"%s", __func__);
}
@end