iOS:Protocol詳解

目錄
一,作用
二,基本使用
三,特點
四,應(yīng)用場景
五,系統(tǒng)協(xié)議
六,底層代碼

一,作用

1,公開方法一般都放在.h文件中,如果想隱藏實現(xiàn)細(xì)節(jié),可以把這些方法放到協(xié)議中,再讓該類遵守此協(xié)議(一個協(xié)議對應(yīng)一個類)

2,將一些公共方法抽取出來封裝成協(xié)議,任何類想擁有這些方法,只需遵守此協(xié)議即可(一個協(xié)議對應(yīng)多個類)

問題:公共方法為什么不放在父類中?
答:下圖中D類跟E類的公共方法可以放在父類B中,但D類跟G類的公共方法放在父類的父類A中顯然是不合適的,這時協(xié)議就能很優(yōu)雅的解決

繼承樹

二,基本使用

1,修飾符

@required:遵守此協(xié)議的類必須實現(xiàn)它修飾的方法(默認(rèn)修飾符)
@optional:遵守此協(xié)議的類可以不實現(xiàn)它修飾的方法

@protocol PersonProtocol <NSObject>
@required
- (void)eat;
@optional
- (void)run;
@end

2,能聲明屬性,但必須在遵守此協(xié)議的類中調(diào)用@syntheszie才能正常使用

// PersonProtocol
@protocol PersonProtocol <NSObject>
@property (nonatomic, copy) NSString *name;
@end

// Person
@interface Person : NSObject <PersonProtocol>
@end

@implementation Person
@synthesize name; // 生成get/set方法的實現(xiàn)
@end

// 使用
Person *person = [Person new];
person.name = @"111";
NSLog(@"name---%@", person.name);

// 打印
name---111

3,不能聲明成員變量

三,特點

1,協(xié)議只有方法的聲明,沒有方法的實現(xiàn)

2,遵守協(xié)議只能在類的聲明@interface上,不能在類的實現(xiàn)@implementation

3,一個協(xié)議可以遵守多個其他協(xié)議

4,一個協(xié)議若遵守了其他協(xié)議,就擁有其他協(xié)議所有方法的聲明

5,一個協(xié)議可以被多個類遵守,一個類可以遵守多個協(xié)議

6,一個類若遵守了某個協(xié)議,就必須實現(xiàn)協(xié)議中@required修飾的方法

7,若父類遵守了某個協(xié)議,子類也就遵守了此協(xié)議

四,應(yīng)用場景

1,不同的類使用統(tǒng)一入口傳遞數(shù)據(jù)(一個協(xié)議對應(yīng)多個類)

// 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)]) { // 是否遵守此協(xié)議
        [obj setData:datas[idx]];
    }
}];

// 打印
view---111
tableView---222

2,面向接口編程:將接口(聲明)和實現(xiàn)分離,對外只暴露接口(一個協(xié)議對應(yīng)一個類)

  • 圖解
面向接口編程
  • bridge:關(guān)聯(lián)接口和實現(xiàn)
// .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:接口的具體實現(xiàn)
@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:使用接口的業(yè)務(wù)
id<ServerProtocol> server = [ServerBridge serverForProtocol:@protocol(ServerProtocol)];
NSLog(@"%@", server.provideData);
[server doSomething];

// 打印
server provide data
server do something

3,控制鏈?zhǔn)骄幊痰恼{(diào)用順序

// .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"); // 不能改變調(diào)用順序
}];
NSLog(@"%@", sql);

// 打印
111222333

五,系統(tǒng)協(xié)議

1,NSObject:根協(xié)議,其他協(xié)議都要遵守它,它提供了很多基本的方法,基類NSObject已經(jīng)遵守此協(xié)議并實現(xiàn)了協(xié)議方法,所以我們可以直接使用這些方法

@protocol NSObject
- (id)performSelector:(SEL)aSelector;
- (BOOL)isKindOfClass:(Class)aClass;
- (BOOL)respondsToSelector:(SEL)aSelector;
...
@end

2,NSCopying:與對象拷貝相關(guān)的協(xié)議,如果想讓某個自定義類具備拷貝功能,那么該類必須遵守此協(xié)議并實現(xiàn)協(xié)議方法

  • 聲明
@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:如果想用歸檔存儲某個自定義類對象,那么該類必須遵守此協(xié)議并實現(xiàn)協(xié)議方法

  • 聲明
@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基礎(chǔ)上增加了安全性

@protocol NSSecureCoding <NSCoding>
@property (class, readonly) BOOL supportsSecureCoding;
@end

六,底層代碼

1,protocol_t結(jié)構(gòu)體

struct protocol_t : objc_object {
    const char *mangledName;                // 重整的名稱
    const char *_demangledName;             // 沒有重整的名稱
    struct protocol_list_t *protocols;      // 遵守的協(xié)議
    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;
    // 從當(dāng)前類到父類逐個進(jìn)行查找
    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函數(shù)
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());

    // 跟類遵守的協(xié)議逐個進(jìn)行比較
    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函數(shù)
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;
        // 跟協(xié)議遵守的協(xié)議逐個進(jìn)行比較
        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;
            }
            // 遞歸調(diào)用
            if (protocol_conformsToProtocol_nolock(proto, other)) {
                return YES;
            }
        }
    }

    return NO;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • protocol 的本質(zhì)類似一個抽象類,這個聲明了一些純虛方法.并且沒有屬性,在java中,這個叫接口類,在c++...
    whitekite閱讀 935評論 1 1
  • Protocol官方文檔 協(xié)議聲明任何類可以選擇實現(xiàn)的編程接口。 協(xié)議允許兩個繼承關(guān)系的類可以相互通信以實現(xiàn)一定的...
    NieFeng1024閱讀 333評論 0 0
  • 基本用途 可以用來聲明很多方法不能聲明成員變量,只有.h文件 只要某個類遵守了這個協(xié)議,就相當(dāng)于擁有了這個協(xié)議中的...
    iOS_July閱讀 575評論 0 0
  • 前言 最近用ProtocolBuf協(xié)議進(jìn)行網(wǎng)絡(luò)傳輸,數(shù)據(jù)也是轉(zhuǎn)為ProtocolBuf。記錄下使用流程 Proto...
    羽裳有涯閱讀 415評論 0 0
  • 劉老漢一手吊著煙斗,手里抓著麻將牌。 “趕緊打啊,老劉,磨蹭什么呢。 “三萬”,別動,別動啊。糊了,我糊了。劉老漢...
    程黃閱讀 415評論 0 2

友情鏈接更多精彩內(nèi)容