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
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 202,607评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,047评论 2 379
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 149,496评论 0 335
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,405评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,400评论 5 364
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,479评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,883评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,535评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,743评论 1 295
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,544评论 2 319
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,612评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,309评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,881评论 3 306
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,891评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,136评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,783评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,316评论 2 342

推荐阅读更多精彩内容

  • 这个女人,同以前简直判若两人。或许以前,我是为了生存,为了自己那自卑的虚荣心,也为了自己青春期的一些生理需求,算是...
    晏大仙阅读 189评论 0 0
  • 我在《好好学习》APP中,学习了顾颉刚老师的史学著作《国史讲话:上古》。 《国史讲话:上古》讲稿文字脉络清晰,逻辑...
    今朝花树下阅读 326评论 0 0
  • 妾在江水下,君在江水头。 江水何迢迢,绵绵思不休。 日日怨江水,恨不溯其游。 欲乘江水去,意恐难同修。 妾居江水下...
    花间娘子阅读 444评论 3 3