目录
一,作用
二,基本使用
三,特点
四,应用场景
五,系统协议
六,底层代码
一,作用
1,公开方法一般都放在.h
文件中,如果想隐藏实现细节,可以把这些方法放到协议中,再让该类遵守此协议(一个协议对应一个类)
2,将一些公共方法抽取出来封装成协议,任何类想拥有这些方法,只需遵守此协议即可(一个协议对应多个类)
问题:公共方法为什么不放在父类中?
答:下图中D
类跟E
类的公共方法可以放在父类B
中,但D
类跟G
类的公共方法放在父类的父类A
中显然是不合适的,这时协议就能很优雅的解决
二,基本使用
1,修饰符
@required
:遵守此协议的类必须实现它修饰的方法(默认修饰符)
@optional
:遵守此协议的类可以不实现它修饰的方法
@protocol PersonProtocol <NSObject>
@required
- (void)eat;
@optional
- (void)run;
@end
2,能声明属性,但必须在遵守此协议的类中调用@syntheszie
才能正常使用
// PersonProtocol
@protocol PersonProtocol <NSObject>
@property (nonatomic, copy) NSString *name;
@end
// Person
@interface Person : NSObject <PersonProtocol>
@end
@implementation Person
@synthesize name; // 生成get/set方法的实现
@end
// 使用
Person *person = [Person new];
person.name = @"111";
NSLog(@"name---%@", person.name);
// 打印
name---111
3,不能声明成员变量
三,特点
1,协议只有方法的声明,没有方法的实现
2,遵守协议只能在类的声明@interface
上,不能在类的实现@implementation
上
3,一个协议可以遵守多个其他协议
4,一个协议若遵守了其他协议,就拥有其他协议所有方法的声明
5,一个协议可以被多个类遵守,一个类可以遵守多个协议
6,一个类若遵守了某个协议,就必须实现协议中@required
修饰的方法
7,若父类遵守了某个协议,子类也就遵守了此协议
四,应用场景
1,不同的类使用统一入口传递数据(一个协议对应多个类)
// CustomViewProtocol
@protocol CustomViewProtocol <NSObject>
- (void)setData:(id)data;
@end
// CustomView
@interface CustomView : UIView <CustomViewProtocol>
@end
@implementation CustomView
- (void)setData:(id)data {
NSLog(@"view---%@", data);
}
@end
// CustomTableView
@interface CustomTableView : UITableView <CustomViewProtocol>
@end
@implementation CustomTableView
- (void)setData:(id)data {
NSLog(@"tableView---%@", data);
}
@end
// 使用
NSArray *views = @[[CustomView new], [CustomTableView new]];
NSArray *datas = @[@"111", @"222"];
[views enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
if ([obj conformsToProtocol:@protocol(CustomViewProtocol)]) { // 是否遵守此协议
[obj setData:datas[idx]];
}
}];
// 打印
view---111
tableView---222
2,面向接口编程:将接口(声明)和实现分离,对外只暴露接口(一个协议对应一个类)
- 图解
-
bridge
:关联接口和实现
// .h文件
@interface ServerBridge : NSObject
+ (void)bindServer:(id)server andProtocol:(Protocol *)protocol;
+ (id)serverForProtocol:(Protocol *)protocol;
@end
// .m文件
@interface ServerBridge ()
@property (nonatomic, strong) NSMutableDictionary<NSString *, id> *serverStore;
@end
@implementation ServerBridge
- (NSMutableDictionary<NSString *,id> *)serverStore {
if (!_serverStore) {
_serverStore = [NSMutableDictionary new];
}
return _serverStore;
}
+ (instancetype)shared {
static id _bridge = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_bridge = [[self alloc] init];
});
return _bridge;
}
+ (void)bindServer:(id)server andProtocol:(Protocol *)protocol {
if ([server conformsToProtocol:protocol]) {
[[ServerBridge shared].serverStore setValue:server
forKey:NSStringFromProtocol(protocol)];
}
}
+ (id)serverForProtocol:(Protocol *)protocol {
return [[ServerBridge shared].serverStore valueForKey:NSStringFromProtocol(protocol)];
}
@end
-
protocol
:对外暴露的接口
@protocol ServerProtocol <NSObject>
@property (nonatomic, copy) NSString *provideData;
- (void)doSomething;
@end
-
server
:接口的具体实现
@interface Server () <ServerProtocol>
@end
@implementation Server
@synthesize provideData;
+ (void)load {
[ServerBridge bindServer:[self new]
andProtocol:@protocol(ServerProtocol)];
}
- (NSString *)provideData {
return @"server provide data";
}
- (void)doSomething {
NSLog(@"server do something");
}
@end
-
business
:使用接口的业务
id<ServerProtocol> server = [ServerBridge serverForProtocol:@protocol(ServerProtocol)];
NSLog(@"%@", server.provideData);
[server doSomething];
// 打印
server provide data
server do something
3,控制链式编程的调用顺序
// .h文件
@class SQLTool;
@protocol Fromable;
@protocol Whereable;
typedef SQLTool<Fromable>*(^Select)(NSString *string);
typedef SQLTool<Whereable>*(^From)(NSString *string);
typedef SQLTool*(^Where)(NSString *string);
@protocol Selectable <NSObject>
@property (nonatomic, copy, readonly) Select select;
@end
@protocol Fromable <NSObject>
@property (nonatomic, copy, readonly) From from;
@end
@protocol Whereable <NSObject>
@property (nonatomic, copy, readonly) Where where;
@end
@interface SQLTool : NSObject
+ (NSString *)makeSQL:(void(^)(SQLTool<Selectable> *tool))block;
@end
// .m文件
@interface SQLTool() <Selectable, Fromable, Whereable>
@property (nonatomic, copy) NSString *sql;
@end
@implementation SQLTool
- (NSString *)sql {
if (!_sql) {
_sql = [NSString new];
}
return _sql;
}
+ (NSString *)makeSQL:(void(^)(SQLTool<Selectable> *tool))block {
if (block) {
SQLTool *tool = [SQLTool new];
block(tool);
return tool.sql;
}
return nil;
}
- (Select)select {
return ^(NSString *string) {
self.sql = [self.sql stringByAppendingString:string];
return self;
};
}
- (From)from {
return ^(NSString *string) {
self.sql = [self.sql stringByAppendingString:string];
return self;
};
}
- (Where)where {
return ^(NSString *string) {
self.sql = [self.sql stringByAppendingString:string];
return self;
};
}
@end
// 使用
NSString *sql = [SQLTool makeSQL:^(SQLTool<Selectable> *tool) {
tool.select(@"111").from(@"222").where(@"333"); // 不能改变调用顺序
}];
NSLog(@"%@", sql);
// 打印
111222333
五,系统协议
1,NSObject
:根协议,其他协议都要遵守它,它提供了很多基本的方法,基类NSObject
已经遵守此协议并实现了协议方法,所以我们可以直接使用这些方法
@protocol NSObject
- (id)performSelector:(SEL)aSelector;
- (BOOL)isKindOfClass:(Class)aClass;
- (BOOL)respondsToSelector:(SEL)aSelector;
...
@end
2,NSCopying
:与对象拷贝相关的协议,如果想让某个自定义类具备拷贝功能,那么该类必须遵守此协议并实现协议方法
- 声明
@protocol NSCopying
- (id)copyWithZone:(NSZone *)zone;
@end
- 使用
// Person
@interface Person : NSObject <NSCopying>
@property (nonatomic, copy) NSString *name;
@end
@implementation Person
- (id)copyWithZone:(NSZone *)zone {
Person *person = [[Person allocWithZone:zone] init];
person.name = self.name;
return person;
}
@end
// 使用
Person *person1 = [Person new];
person1.name = @"123";
Person *person2 = [person1 copy];
person1.name = @"456";
NSLog(@"%@", person1.name);
NSLog(@"%@", person2.name);
// 打印
456
123
3,NSMutableCopying
:让自定义类具备可变拷贝功能
@protocol NSMutableCopying
- (id)mutableCopyWithZone:(NSZone *)zone;
@end
4,NSCoding
:如果想用归档存储某个自定义类对象,那么该类必须遵守此协议并实现协议方法
- 声明
@protocol NSCoding
- (void)encodeWithCoder:(NSCoder *)aCoder;
- (instancetype)initWithCoder:(NSCoder *)aDecoder;
@end
- 使用
// Person
@interface Person : NSObject <NSCoding>
@property (nonatomic, copy) NSString *name;
@end
@implementation Person
- (void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeObject:self.name forKey:@"name"];
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
if (self = [super init]) {
self.name = [aDecoder decodeObjectForKey:@"name"];
}
return self;
}
@end
// 使用
- (void)viewDidLoad {
[super viewDidLoad];
[self save];
[self read];
}
- (NSString *)filePath {
NSString *document = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
return [document stringByAppendingPathComponent:@"Person.data"];
}
- (void)save {
Person *person = [Person new];
person.name = @"111";
[NSKeyedArchiver archiveRootObject:person toFile:self.filePath];
}
- (void)read {
Person *person = [NSKeyedUnarchiver unarchiveObjectWithFile:self.filePath];
NSLog(@"%@", person.name);
}
// 打印
111
5,NSSecureCoding
:在NSCoding
基础上增加了安全性
@protocol NSSecureCoding <NSCoding>
@property (class, readonly) BOOL supportsSecureCoding;
@end
六,底层代码
1,protocol_t
结构体
struct protocol_t : objc_object {
const char *mangledName; // 重整的名称
const char *_demangledName; // 没有重整的名称
struct protocol_list_t *protocols; // 遵守的协议
method_list_t *classMethods; // 类方法
method_list_t *optionalClassMethods; // 可选的类方法
method_list_t *instanceMethods; // 实例方法
method_list_t *optionalInstanceMethods; // 可选的实例方法
property_list_t *_classProperties; // 类属性
property_list_t *instanceProperties; // 实例属性
...
}
2,conformsToProtocol:
方法
- 类方法和实例方法
+ (BOOL)conformsToProtocol:(Protocol *)protocol {
if (!protocol) return NO;
// 从当前类到父类逐个进行查找
for (Class tcls = self; tcls; tcls = tcls->superclass) {
if (class_conformsToProtocol(tcls, protocol)) return YES;
}
return NO;
}
- (BOOL)conformsToProtocol:(Protocol *)protocol {
if (!protocol) return NO;
for (Class tcls = self.class; tcls; tcls = tcls->superclass) {
if (class_conformsToProtocol(tcls, protocol)) return YES;
}
return NO;
}
-
class_conformsToProtocol
函数
BOOL class_conformsToProtocol(Class cls, Protocol *proto_gen) {
protocol_t *proto = newprotocol(proto_gen);
if (!cls) return NO;
if (!proto_gen) return NO;
rwlock_reader_t lock(runtimeLock);
assert(cls->isRealized());
// 跟类遵守的协议逐个进行比较
for (const auto& proto_ref : cls->data()->protocols) {
protocol_t *p = remapProtocol(proto_ref);
if (p == proto || protocol_conformsToProtocol_nolock(p, proto)) {
return YES;
}
}
return NO;
}
-
protocol_conformsToProtocol_nolock
函数
static bool protocol_conformsToProtocol_nolock(protocol_t *self, protocol_t *other) {
runtimeLock.assertLocked();
if (!self || !other) {
return NO;
}
if (0 == strcmp(self->mangledName, other->mangledName)) {
return YES;
}
if (self->protocols) {
uintptr_t i;
// 跟协议遵守的协议逐个进行比较
for (i = 0; i < self->protocols->count; i++) {
protocol_t *proto = remapProtocol(self->protocols->list[i]);
if (0 == strcmp(other->mangledName, proto->mangledName)) {
return YES;
}
// 递归调用
if (protocol_conformsToProtocol_nolock(proto, other)) {
return YES;
}
}
}
return NO;
}