@protocol SportProtocol <NSObject>
- (void)playFootball;
- (void)playBasketball;
- (void)run;
@end
#import <Foundation/Foundation.h>
#import "SportProtocol.h"
@interface Person : NSObject<SportProtocol>
@end
Protocol:
@protocol SportProtocol <NSObject>
@property (nonatomic,copy) NSString *sportType;
- (void)playFootball;
- (void)playBasketball;
- (void)run;
@end
实现类:
#import <Foundation/Foundation.h>
#import "SportProtocol.h"
@interface Person : NSObject<SportProtocol>
@end
#import "Person.h"
@implementation Person
@synthesize sportType=_sportType;
- (void)readSportType{
NSLog(@"%@",_sportType);
}
@end
上面方法中主要用到了@synthesize sportType=_sportType, 意思是说,sportType 属性为 _sportType 成员变量合成访问器方法。
Person *p =[[Person alloc]init];
p.sportType = @"sport";
[p readSportType];
#import <Foundation/Foundation.h>
#import "SportProtocol.h"
@interface Person : NSObject<SportProtocol>
@end
----------------------
#import "Person.h"
@interface Student : Person
@end
----------------------
Student *stu = [[Student alloc]init];
[stu playBasketball];
#import <Foundation/Foundation.h>
#import "SportProtocol.h"
#import "StudyProtocol.h"
@interface Person : NSObject<SportProtocol,StudyProtocol>
@end
#import <Foundation/Foundation.h>
#import "BaseProtocol.h"
@protocol StudyProtocol <BaseProtocol>
- (void)studyEnglish;
- (void)studyChinese;
@end
#import <Foundation/Foundation.h>
@protocol BaseProtocol <NSObject>
@end
@protocol SportProtocol <NSObject>
@required
- (void)playFootball;
- (void)playBasketball;
@optional
- (void)run;
- (void)readSportType;
@end
要求: 一个人需要一个app,这个app必须有学习、买东西、分享等功能 处理思路: 1、需要创建一个人和APP 2、需要创建一个Protocol来描述这些功能 3、人拥有的APP要实现这些功能 4、APP需要遵循这个Protocol且实现它
#import <Foundation/Foundation.h>
@protocol DoSomethingProtocol <NSObject>
- (void)buySomething;
- (void)studyEnglish;
- (void)shareInfo;
@end
----------------------------
#import <Foundation/Foundation.h>
#import "DoSomethingProtocol.h"
@class APP;
@interface Person : NSObject
//拥有的APP要实现Protocol的功能
@property (nonatomic,strong) APP<DoSomethingProtocol> *app;
@end
----------------------------
#import <Foundation/Foundation.h>
#import "DoSomethingProtocol.h"
@interface APP : NSObject<DoSomethingProtocol>
@end
#import "APP.h"
@implementation APP
- (void)buySomething {
NSLog(@"%s",__func__);
}
- (void)shareInfo {
NSLog(@"%s",__func__);
}
- (void)studyEnglish {
NSLog(@"%s",__func__);
}
@end
----------------------------
Person *p = [[Person alloc]init];
APP *app = [[APP alloc]init];
//赋值的时候就会判断app是否是符合协议的app,如果app没有遵循协议就会报警告
p.app = app;
//判断app是否有实现协议内容
if([p.app respondsToSelector:@selector(buySomething)]){
[p.app buySomething];
}
if ([p.app respondsToSelector:@selector(studyEnglish)]) {
[p.app studyEnglish];
}
if ([p.app respondsToSelector:@selector(shareInfo)]) {
[p.app shareInfo];
}