iOS之runtime详解api(四)

今天,讲这个系列的第四篇,是关于Protocol

5.Protocol

首先,我们依然寻找最简单的方法:

const char * _Nonnull
protocol_getName(Protocol * _Nonnull proto)
OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0, 2.0);
复制代码

这个方法是获得协议的名称。后面我们打印协议就通过这个函数。 既然可以通过协议来获取名称,那么也可以通过名称来获取协议,就是下面这个方法:

Protocol * _Nullable
objc_getProtocol(const char * _Nonnull name)
OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0, 2.0);
复制代码

我们新建一个协议类PlayProtocol:

-(void)protocolCommen {
    Protocol *protocol = objc_getProtocol("PlayProtocol");
    if (protocol) {
        const char* name = protocol_getName(protocol);
        NSLog(@"name = %s",name);
    }else {
        NSLog(@"不存在该协议");
    }
}
复制代码

运行结果:

不存在该协议
复制代码

奇了怪了,明明新建了,为什么找不到了,是不是因为没有使用呢? 我们随便找个类去遵循这个协议,就拿我们前几篇新建的那个Person类吧。 再运行一次:

name = PlayProtocol
复制代码

这次没错了,最后的结论是,必须**register**(只要有Class遵循这个Protocol,就算register)的Protocol才能通过objc_getProtocol找到。 下面这个方法是判断a协议是否遵循b协议:

BOOL
protocol_conformsToProtocol(Protocol * _Nullable proto,
                            Protocol * _Nullable other)
OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0, 2.0);
复制代码

我们新建一个SingProtocol协议,让PlayProtocol遵循SingProtocol协议,即

@protocol PlayProtocol <SingProtocol>

@end
复制代码

我们来实践一下吧:

-(void)conformsToProtocol {
    Protocol* playProtocol = objc_getProtocol("PlayProtocol");
    Protocol* singProtocol = objc_getProtocol("SingProtocol");

    BOOL isConform = protocol_conformsToProtocol(playProtocol, singProtocol);
    NSLog(@"PlayProtocol协议  %@ SingProtocol协议",isConform?@"遵循":@"不遵循");
    BOOL isConform2 = protocol_conformsToProtocol(singProtocol, playProtocol);
    NSLog(@"SingProtocol协议  %@ PlayProtocol协议",isConform2?@"遵循":@"不遵循");

}
复制代码

运行结果:

2019-02-28 09:41:30.362087+0800 Runtime-Demo[86769:5791422] PlayProtocol协议  遵循 SingProtocol协议
2019-02-28 09:41:30.362134+0800 Runtime-Demo[86769:5791422] SingProtocol协议  不遵循 PlayProtocol协议
复制代码

我们可以PlayProtocol协议遵循了SingProtocol协议。 下面这个方法是指判断2个协议是否相等。

BOOL
protocol_isEqual(Protocol * _Nullable proto, Protocol * _Nullable other)
OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0, 2.0);
复制代码

我们新建一个RunProtocol协议也遵循SingProtocol。因为我们之前PlayProtocol协议也遵循了SingProtocol协议,并且这两个协议都没有各自的方法。那我们来测试下:

-(void)isEqual {
    Protocol* playProtocol = objc_getProtocol("PlayProtocol");
    Protocol* runProtocol = objc_getProtocol("SingProtocol");
    BOOL isEqual = protocol_isEqual(playProtocol, runProtocol);
    NSLog(@"%@",isEqual?@"相等":@"不相等");
}
复制代码

运行之后:

不相等
复制代码

又一次出乎意料,难道真的只有完全相等才行吗?看下源码吧:

BOOL protocol_isEqual(Protocol *self, Protocol *other)
{
    if (self == other) return YES;
    if (!self  ||  !other) return NO;

    if (!protocol_conformsToProtocol(self, other)) return NO;
    if (!protocol_conformsToProtocol(other, self)) return NO;

    return YES;
}
复制代码

真的是只有完全相等才能返回YES: 那么我们改下代码:

-(void)isEqual2 {
    Protocol* playProtocol1 = objc_getProtocol("PlayProtocol");
    NSLog(@"playProtocol1 = %@",playProtocol1);
    Protocol* playProtocol2 = objc_getProtocol("PlayProtocol");
    NSLog(@"playProtocol2 = %@",playProtocol2);
    BOOL isEqual = protocol_isEqual(playProtocol1, playProtocol2);
    NSLog(@"%@",isEqual?@"相等":@"不相等");
}
复制代码

运行结果:

2019-02-28 10:18:07.799200+0800 Runtime-Demo[87377:5813138] playProtocol1 = <Protocol: 0x10463e9a0>
2019-02-28 10:18:07.799250+0800 Runtime-Demo[87377:5813138] playProtocol2 = <Protocol: 0x10463e9a0>
2019-02-28 10:18:07.799301+0800 Runtime-Demo[87377:5813138] 相等
复制代码

只有当两个协议对象完全相同(内存地址一样),才能返回YES

下面两个方法也是和Method有关。

struct objc_method_description
protocol_getMethodDescription(Protocol * _Nonnull proto, SEL _Nonnull aSel,
                              BOOL isRequiredMethod, BOOL isInstanceMethod)
OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0, 2.0);

struct objc_method_description * _Nullable
protocol_copyMethodDescriptionList(Protocol * _Nonnull proto,
                                   BOOL isRequiredMethod,
                                   BOOL isInstanceMethod,
                                   unsigned int * _Nullable outCount)
OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0, 2.0);
复制代码

protocol_getMethodDescription找到某个协议的某个方法,protocol_copyMethodDescriptionList找到某个协议的所有方法。我们在SingProtocol协议里面加几个方法:

@protocol SingProtocol <NSObject>

@required
-(void)singFolkSongs;
+(void)singRockSongs;

@optional
-(void)singPopularSongs;
+(void)singMetalSongs;
@end
复制代码

我们先实践下protocol_getMethodDescriptionprotocol_getMethodDescription有4个参数,proto指定的协议,aSel指定的方法,isRequiredMethod是否是必要方法,isInstanceMethod是否是实例方法:

-(void)getMethodDescription  {
    Protocol* singProtocol = objc_getProtocol("SingProtocol");
    struct objc_method_description method =  protocol_getMethodDescription(singProtocol, sel_registerName("singFolkSongs"), YES, YES);
    NSLog(@"singFolkSongs方法 name = %s,types = %s", sel_getName(method.name)  ,method.types);
    
    struct objc_method_description method1 =  protocol_getMethodDescription(singProtocol, sel_registerName("singRockSongs"), YES, NO);
    NSLog(@"singRockSongs方法 name = %s,types = %s", sel_getName(method1.name)  ,method1.types);
    
    struct objc_method_description method2 =  protocol_getMethodDescription(singProtocol, sel_registerName("singPopularSongs"), NO, YES);
    NSLog(@"singPopularSongs方法 name = %s,types = %s", sel_getName(method2.name)  ,method2.types);
    
    struct objc_method_description method3 =  protocol_getMethodDescription(singProtocol, sel_registerName("singMetalSongs"), NO, NO);
    NSLog(@"singMetalSongs方法 name = %s,types = %s", sel_getName(method3.name)  ,method3.types);
}
复制代码

运行结果:

2019-02-28 10:37:32.929473+0800 Runtime-Demo[87693:5820462] singFolkSongs方法 name = singFolkSongs,types = v16@0:8
2019-02-28 10:37:32.929514+0800 Runtime-Demo[87693:5820462] singRockSongs方法 name = singRockSongs,types = v16@0:8
2019-02-28 10:37:32.929528+0800 Runtime-Demo[87693:5820462] singPopularSongs方法 name = singPopularSongs,types = v16@0:8
2019-02-28 10:37:32.929540+0800 Runtime-Demo[87693:5820462] singMetalSongs方法 name = singMetalSongs,types = v16@0:8
复制代码

运行结果没毛病!!! 我们再看下protocol_copyMethodDescriptionList这个函数,是用来找某个协议符合条件的方法列表,参数含义和protocol_getMethodDescription类似,那么我就直接试炼了:

-(void)copyMethodDescriptionList {
    Protocol* singProtocol = objc_getProtocol("SingProtocol");
    unsigned int count1;
    struct objc_method_description *methodList1 =   protocol_copyMethodDescriptionList(singProtocol, YES, YES, &count1);
    NSLog(@"-----必要方法以及实例方法-----");
    for (unsigned int i = 0; i < count1; i++) {
        struct objc_method_description method = methodList1[i];
        NSLog(@"name = %s,types = %s", sel_getName(method.name)  ,method.types);

    }
    free(methodList1);
    
    unsigned int count2;
    struct objc_method_description *methodList2 =   protocol_copyMethodDescriptionList(singProtocol, YES, NO, &count2);
    NSLog(@"-----必要方法以及类方法-----");
    for (unsigned int i = 0; i < count2; i++) {
        struct objc_method_description method = methodList2[i];
        NSLog(@"name = %s,types = %s", sel_getName(method.name)  ,method.types);
        
    }
    free(methodList2);

    
    unsigned int count3;
    struct objc_method_description *methodList3 =   protocol_copyMethodDescriptionList(singProtocol, NO, NO, &count3);
    NSLog(@"-----可选方法以及类方法-----");
    for (unsigned int i = 0; i < count3; i++) {
        struct objc_method_description method = methodList3[i];
        NSLog(@"name = %s,types = %s", sel_getName(method.name)  ,method.types);
        
    }
    free(methodList3);

    
    unsigned int count4;
    struct objc_method_description *methodList4 =   protocol_copyMethodDescriptionList(singProtocol, NO, YES, &count4);
    NSLog(@"-----可选方法以及实例方法-----");
    for (unsigned int i = 0; i < count4; i++) {
        struct objc_method_description method = methodList4[i];
        NSLog(@"name = %s,types = %s", sel_getName(method.name)  ,method.types);
        
    }
    free(methodList4);

}
复制代码

运行结果:

2019-02-28 10:46:29.075801+0800 Runtime-Demo[87839:5823598] -----必要方法以及实例方法-----
2019-02-28 10:46:29.075836+0800 Runtime-Demo[87839:5823598] name = singFolkSongs,types = v16@0:8
2019-02-28 10:46:29.075849+0800 Runtime-Demo[87839:5823598] -----必要方法以及类方法-----
2019-02-28 10:46:29.075857+0800 Runtime-Demo[87839:5823598] name = singRockSongs,types = v16@0:8
2019-02-28 10:46:29.075866+0800 Runtime-Demo[87839:5823598] -----可选方法以及类方法-----
2019-02-28 10:46:29.075873+0800 Runtime-Demo[87839:5823598] name = singMetalSongs,types = v16@0:8
2019-02-28 10:46:29.075882+0800 Runtime-Demo[87839:5823598] -----可选方法以及实例方法-----
2019-02-28 10:46:29.075889+0800 Runtime-Demo[87839:5823598] name = singPopularSongs,types = v16@0:8
复制代码

和我们分析的一样。 既然可以从协议里获得方法,那么也可以获得协议里的属性:

objc_property_t _Nullable
protocol_getProperty(Protocol * _Nonnull proto,
                     const char * _Nonnull name,
                     BOOL isRequiredProperty, BOOL isInstanceProperty)
OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0, 2.0);

objc_property_t _Nonnull * _Nullable
protocol_copyPropertyList(Protocol * _Nonnull proto,
                          unsigned int * _Nullable outCount)
OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0, 2.0);

objc_property_t _Nonnull * _Nullable
protocol_copyPropertyList2(Protocol * _Nonnull proto,
                           unsigned int * _Nullable outCount,
                           BOOL isRequiredProperty, BOOL isInstanceProperty)
OBJC_AVAILABLE(10.12, 10.0, 10.0, 3.0, 2.0);
复制代码

protocol_getProperty是获取协议里的属性,protocol_copyPropertyListprotocol_copyPropertyList2都是获取协议里的属性列表。protocol_copyPropertyList2是更加细分条件的去获取协议里的属性列表。 我们在SingProtocol里添加若干属性,如下:

@protocol SingProtocol <NSObject>

@required
-(void)singFolkSongs;
+(void)singRockSongs;
@property(nonatomic,copy)NSString* folkSongs;
@property(nonatomic,copy,class)NSString* rockSongs;
@optional
-(void)singPopularSongs;
+(void)singMetalSongs;
@property(nonatomic,copy)NSString* popularSongs;
@property(nonatomic,copy,class)NSString* metalSongs;

@end
复制代码

在上面我们看到了陌生的class关键词,iOS8之后,LLVM已经支持显式声明类属性了,这是为了与Swift中的类属性互操作而引入的,大家可以找下相关文档。 另外在协议的属性里面,是不分@optional@required,我们在源码里可以看到:

static property_t * 
protocol_getProperty_nolock(protocol_t *proto, const char *name, 
                            bool isRequiredProperty, bool isInstanceProperty)
{
    runtimeLock.assertLocked();

    if (!isRequiredProperty) {
        // Only required properties are currently supported.
        return nil;
    }

    property_list_t *plist = isInstanceProperty ? 
        proto->instanceProperties : proto->classProperties();
    if (plist) {
        for (auto& prop : *plist) {
            if (0 == strcmp(name, prop.name)) {
                return &prop;
            }
        }
    }

    if (proto->protocols) {
        uintptr_t i;
        for (i = 0; i < proto->protocols->count; i++) {
            protocol_t *p = remapProtocol(proto->protocols->list[i]);
            property_t *prop = 
                protocol_getProperty_nolock(p, name, 
                                            isRequiredProperty, 
                                            isInstanceProperty);
            if (prop) return prop;
        }
    }

    return nil;
}
复制代码

protocol_getProperty的底层就是调用的这个方法,我们可以看到里面:

 if (!isRequiredProperty) {
        // Only required properties are currently supported.
        return nil;
 }
复制代码

这里明确说明了目前只支持required的属性,一旦传入isRequiredPropertyNO的话,直接返回nil。 知道了这些概念,我们实践下:

-(void)getProperty_Protocol {
    Protocol* singProtocol = objc_getProtocol("SingProtocol");
    objc_property_t rockSongsProperty = protocol_getProperty(singProtocol, "rockSongs", YES, NO);
    const char* rockSongsName = property_getName(rockSongsProperty);
    NSLog(@"rockSongs 属性 name = %s",rockSongsName);
    
    objc_property_t folkSongsProperty = protocol_getProperty(singProtocol, "folkSongs", YES, YES);
    const char* folkSongsName = property_getName(folkSongsProperty);
    NSLog(@"folkSongs 属性 name = %s",folkSongsName);
    
    objc_property_t popularSongsProperty = protocol_getProperty(singProtocol, "popularSongs", YES, YES);
    const char* popularSongsName = property_getName(popularSongsProperty);
    NSLog(@"popularSongs 属性 name = %s",popularSongsName);
    
    objc_property_t metalSongsProperty = protocol_getProperty(singProtocol, "metalSongs", YES, NO);
    const char* metalSongsName = property_getName(metalSongsProperty);
    NSLog(@"metalSongs 属性 name = %s",metalSongsName);
}
复制代码

打印结果:

2019-02-28 11:49:17.619145+0800 Runtime-Demo[88910:5849614] rockSongs 属性 name = rockSongs
2019-02-28 11:49:17.619184+0800 Runtime-Demo[88910:5849614] folkSongs 属性 name = folkSongs
2019-02-28 11:49:17.619196+0800 Runtime-Demo[88910:5849614] popularSongs 属性 name = popularSongs
2019-02-28 11:49:17.619207+0800 Runtime-Demo[88910:5849614] metalSongs 属性 name = metalSongs
复制代码

没毛病!!! 同样,我们实践下protocol_copyPropertyListprotocol_copyPropertyList2方法:

-(void)copyPropertyList_protocol {
    Protocol* singProtocol = objc_getProtocol("SingProtocol");

    NSLog(@"-----copyPropertyList------");
    unsigned int count;
    objc_property_t* propertyList = protocol_copyPropertyList(singProtocol, &count);
    for (unsigned int i = 0; i < count; i++) {
        objc_property_t property = propertyList[i];
        NSLog(@"name = %s",property_getName(property));
    }
    free(propertyList);

    NSLog(@"-----copyPropertyList2---instance propertys---");
    unsigned int count2;
    objc_property_t* propertyList2 = protocol_copyPropertyList2(singProtocol, &count2, YES, YES);
    for (unsigned int i = 0; i < count2; i++) {
        objc_property_t property = propertyList2[i];
        NSLog(@"name = %s",property_getName(property));
    }
    free(propertyList2);
    NSLog(@"-----copyPropertyList2---class propertys---");
    unsigned int count3;
    objc_property_t* propertyList3 = protocol_copyPropertyList2(singProtocol, &count3, YES, NO);
    for (unsigned int i = 0; i < count3; i++) {
        objc_property_t property = propertyList3[i];
        NSLog(@"name = %s",property_getName(property));
    }
    free(propertyList3);
}
复制代码

运行结果:

2019-02-28 13:30:34.259328+0800 Runtime-Demo[90302:5888309] -----copyPropertyList------
2019-02-28 13:30:34.259367+0800 Runtime-Demo[90302:5888309] name = folkSongs
2019-02-28 13:30:34.259378+0800 Runtime-Demo[90302:5888309] name = popularSongs
2019-02-28 13:30:34.259387+0800 Runtime-Demo[90302:5888309] -----copyPropertyList2---instance propertys---
2019-02-28 13:30:34.259395+0800 Runtime-Demo[90302:5888309] name = folkSongs
2019-02-28 13:30:34.259403+0800 Runtime-Demo[90302:5888309] name = popularSongs
2019-02-28 13:30:34.259411+0800 Runtime-Demo[90302:5888309] -----copyPropertyList2---class propertys---
2019-02-28 13:30:34.259418+0800 Runtime-Demo[90302:5888309] name = rockSongs
2019-02-28 13:30:34.259426+0800 Runtime-Demo[90302:5888309] name = metalSongs
复制代码

根据打印结果protocol_copyPropertyList方法只能获得实例属性的属性列表。protocol_copyPropertyList2方法根据你传的isInstanceProperty的不同而返回不同的属性列表(实例属性列表或者类属性列表)。 那么,如何查看一个类是否遵循某个协议呢,当然是下面这个方法:

BOOL
class_conformsToProtocol(Class _Nullable cls, Protocol * _Nullable protocol)
OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0, 2.0);
复制代码

我们已知Person类已经遵循了PlayProtocol,那么测试下:

-(void)conformsToProtocol_class {
    Protocol* playProtocol = objc_getProtocol("PlayProtocol");
    Protocol* runProtocol = objc_getProtocol("RunProtocol");

    BOOL isConforms = class_conformsToProtocol(objc_getClass("Person"), playProtocol);
    BOOL isConforms2 = class_conformsToProtocol(objc_getClass("Person"), runProtocol);

    NSLog(@"Person %@ PlayProtocol协议",isConforms?@"遵循":@"不遵循");
    NSLog(@"Person %@ RunProtocol协议",isConforms2?@"遵循":@"不遵循");
}
复制代码

运行结果:

2019-02-28 13:57:46.292107+0800 Runtime-Demo[90742:5897636] Person 遵循 PlayProtocol协议
2019-02-28 13:57:46.292143+0800 Runtime-Demo[90742:5897636] Person 不遵循 RunProtocol协议
复制代码

完全正确!!!

Protocol * __unsafe_unretained _Nonnull * _Nullable
protocol_copyProtocolList(Protocol * _Nonnull proto,
                          unsigned int * _Nullable outCount)
OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0, 2.0);
复制代码

这个方法是获得一个协议所遵循的协议的列表。新建一个新协议EatProtocol,遵循RunProtocol,SingProtocol,PlayProtocol,并让Person类遵循EatProtocol(目的是能获得这个协议)如下:

@protocol EatProtocol <RunProtocol,SingProtocol,PlayProtocol>

@end
复制代码

准备工作好了,那么久开始了:

-(void)copyProtocolList {
    Protocol* eatProtocol = objc_getProtocol("EatProtocol");
    unsigned int count;
    __unsafe_unretained Protocol** protocolList = protocol_copyProtocolList(eatProtocol, &count);
    
    for (unsigned int i = 0; i < count ; i++) {
        Protocol* protocol = protocolList[i];
        NSLog(@"%s",protocol_getName(protocol));
    }
    
    free(protocolList);
}
复制代码

运行结果:

2019-02-28 14:17:35.718944+0800 Runtime-Demo[91079:5905870] RunProtocol
2019-02-28 14:17:35.718983+0800 Runtime-Demo[91079:5905870] SingProtocol
2019-02-28 14:17:35.718992+0800 Runtime-Demo[91079:5905870] PlayProtocol
复制代码

事实上也遵循了这三个协议。 下面这个方法是获得某个类所遵循的协议数组

Protocol * __unsafe_unretained _Nonnull * _Nullable
class_copyProtocolList(Class _Nullable cls, unsigned int * _Nullable outCount)
OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0, 2.0);
复制代码

我们在Person类里遵循了PlayProtocol,EatProtocol两个协议:

-(void)copyProtocolList_class {
    Class class = objc_getClass("Person");
    unsigned int count;
    __unsafe_unretained Protocol** protocolList = class_copyProtocolList(class, &count);
    for (unsigned int i = 0; i < count ; i++) {
        Protocol* protocol = protocolList[i];
        NSLog(@"%s",protocol_getName(protocol));
    }
    
    free(protocolList);
}
复制代码

运行结果:

2019-02-28 14:26:38.842578+0800 Runtime-Demo[91226:5908955] PlayProtocol
2019-02-28 14:26:38.842616+0800 Runtime-Demo[91226:5908955] EatProtocol
复制代码

Person类事实遵循了PlayProtocol,EatProtocol两个协议。 下面这个函数是获得整个工程里面所遵循的协议:

Protocol * __unsafe_unretained _Nonnull * _Nullable
objc_copyProtocolList(unsigned int * _Nullable outCount)
OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0, 2.0);
复制代码

运行结果:

2019-02-28 14:30:14.378254+0800 Runtime-Demo[91287:5910354] SCNAnimation
2019-02-28 14:30:14.378305+0800 Runtime-Demo[91287:5910354] GEOBatchOpportunisticTileDownloaderDelegate
2019-02-28 14:30:14.378321+0800 Runtime-Demo[91287:5910354] PTSettingsKeyObserver
2019-02-28 14:30:14.378339+0800 Runtime-Demo[91287:5910354] _SFPBUserReportRequest
2019-02-28 14:30:14.378354+0800 Runtime-Demo[91287:5910354] _UIAlertControllerTextFieldViewControllerContaining
2019-02-28 14:30:14.378370+0800 Runtime-Demo[91287:5910354] SFVerticalLayoutCardSection
2019-02-28 14:30:14.378386+0800 Runtime-Demo[91287:5910354] MKInfoCardThemeListener
......
......
复制代码

我们会发现,打印了很多协议,其中大多数都是系统自带的协议,也有我们自定义的协议。 和Class一样还能动态的生成Protocol

Protocol * _Nullable
objc_allocateProtocol(const char * _Nonnull name)
OBJC_AVAILABLE(10.7, 4.3, 9.0, 1.0, 2.0);

void
objc_registerProtocol(Protocol * _Nonnull proto)
OBJC_AVAILABLE(10.7, 4.3, 9.0, 1.0, 2.0);
复制代码

这两个函数和objc_allocateClassPairobjc_registerClassPair一样,必须register才能使用。

-(void)allocateProtocol {
    Protocol* protocol = objc_allocateProtocol("TestProtocol");
    objc_registerProtocol(protocol);
    NSLog(@"%s",protocol_getName(protocol));
}
复制代码

运行结果:

TestProtocol
复制代码

下面几个方法是给协议添加内容的。

void
protocol_addMethodDescription(Protocol * _Nonnull proto, SEL _Nonnull name,
                              const char * _Nullable types,
                              BOOL isRequiredMethod, BOOL isInstanceMethod)
OBJC_AVAILABLE(10.7, 4.3, 9.0, 1.0, 2.0);
复制代码

这个方法是给协议添加Method的。给协议添加方法有两种情况,第一,是给已经创建好并且已经register的协议添加方法,第二,是给动态生成的协议添加方法。 第一种情况:

-(void)addMethodDescription1 {
    Protocol* eatProtocol = objc_getProtocol("EatProtocol");
    SEL selector = sel_registerName("test");
    const char* type = "v@:";
    BOOL isRequiredMethod = YES;
    BOOL isInstanceMethod = YES;
    protocol_addMethodDescription(eatProtocol, selector, type, isRequiredMethod, isInstanceMethod);
    
    struct objc_method_description method =  protocol_getMethodDescription(eatProtocol, sel_registerName("test"), YES, YES);
    NSLog(@"test方法 name = %s,types = %s", sel_getName(method.name)  ,method.types);
}
复制代码

运行结果:

objc[2121]: protocol_addMethodDescription: protocol 'EatProtocol' is not under construction!
2019-03-01 09:30:56.232714+0800 Runtime-Demo[2121:6266526] test方法 name = <null selector>,types = (null)
复制代码

打印结果说EatProtocol不在建设中,添加方法也失败! 第二种情况:

-(void)addMethodDescription2 {
    Protocol* protocol = objc_allocateProtocol("TestProtocol");
    
    SEL selector = sel_registerName("test");
    const char* type = "v@:";
    BOOL isRequiredMethod = YES;
    BOOL isInstanceMethod = YES;
    protocol_addMethodDescription(protocol, selector, type, isRequiredMethod, isInstanceMethod);
    objc_registerProtocol(protocol);

    struct objc_method_description method =  protocol_getMethodDescription(protocol, sel_registerName("test"), YES, YES);
    NSLog(@"test方法 name = %s,types = %s", sel_getName(method.name)  ,method.types);
}
复制代码

运行结果:

2019-03-01 09:32:34.581517+0800 Runtime-Demo[2148:6267322] test方法 name = test,types = v@:
复制代码

下面这个方法是添加属性:

void
protocol_addProperty(Protocol * _Nonnull proto, const char * _Nonnull name,
                     const objc_property_attribute_t * _Nullable attributes,
                     unsigned int attributeCount,
                     BOOL isRequiredProperty, BOOL isInstanceProperty)
OBJC_AVAILABLE(10.7, 4.3, 9.0, 1.0, 2.0);
复制代码

这个函数和protocol_addMethodDescription一样,只有通过objc_allocateProtocol生成的协议才能添加属性。

-(void)addProperty_protocol {
    Protocol* protocol = objc_allocateProtocol("TestProtocol");
    const char* name = "juice";

    unsigned int count = 5;
    objc_property_attribute_t attributeList[count];
    objc_property_attribute_t attribute1 ;
    attribute1.name = "T";
    attribute1.value = "NSString";
    objc_property_attribute_t attribute2 ;
    attribute2.name = "V";
    attribute2.value = "_juice";
    objc_property_attribute_t attribute3 ;
    attribute3.name = "N";
    attribute3.value = "";
    objc_property_attribute_t attribute4 ;
    attribute4.name = "C";
    attribute4.value = "";
    objc_property_attribute_t attribute5 ;
    attribute5.name = "R";
    attribute5.value = "";
    attributeList[0] = attribute1;
    attributeList[1] = attribute2;
    attributeList[2] = attribute3;
    attributeList[3] = attribute4;
    attributeList[4] = attribute5;
    
    BOOL isRequiredProperty = YES;
    BOOL isInstanceProperty = YES;
    protocol_addProperty(protocol, name, (const objc_property_attribute_t*)attributeList, count, isRequiredProperty, isInstanceProperty);
    objc_registerProtocol(protocol);

    objc_property_t property = protocol_getProperty(protocol, "juice", YES, YES);

    NSLog(@"name = %s",property_getName(property));
}
复制代码

运行结果:

name = juice
复制代码

下面的函数是指的是让proto协议遵循addition协议。

void
protocol_addProtocol(Protocol * _Nonnull proto, Protocol * _Nonnull addition)
OBJC_AVAILABLE(10.7, 4.3, 9.0, 1.0, 2.0);
复制代码

proto协议必须是仍在构建当中(alloc但是没有register)而addition是要已经构建好的。我们让TestProtocol遵循SingProtocol协议。

-(void)addProtocol_protocol {
    Protocol* protocol = objc_allocateProtocol("TestProtocol");
    Protocol* protocol2 = objc_getProtocol("SingProtocol");
    protocol_addProtocol(protocol, protocol2);
    objc_registerProtocol(protocol);
    
    BOOL isConform = protocol_conformsToProtocol(protocol, protocol2);
    NSLog(@"isConform = %d",isConform);
}
复制代码

运行结果:

isConform = 1
复制代码

下面这个方法是让一个类遵循protocol协议

BOOL
class_addProtocol(Class _Nullable cls, Protocol * _Nonnull protocol)
OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0, 2.0);
复制代码

目前Cat类没有遵循任何协议,这里我打算让Cat遵循PlayProtocol协议:

-(void)addProtocol_class {
    Protocol* protocol = objc_getProtocol("PlayProtocol");
    Class class = objc_getClass("Cat");
    class_addProtocol(class, protocol);
    BOOL isConform = class_conformsToProtocol(class, protocol);
    NSLog(@"isConform = %d",isConform);
}
复制代码

运行结果:

isConform = 1
复制代码

这样,所有关于Protocol的方法都测试完成了。

猜你喜欢

转载自juejin.im/post/5c80c410f265da2de04ae54d
今日推荐