美文网首页
为什么不能runtime创建JSExport类型的Protoco

为什么不能runtime创建JSExport类型的Protoco

作者: Tomychen | 来源:发表于2017-08-20 18:09 被阅读0次

    JavaScriptCore引入后,js调用OC的方法有了新的实现方式。让一个类遵循一个JSExport的协议,将想要暴露的方法在JSExport协议中声明,即可在js中直接调用到OC的方法。
    例如下面的代码:

    #import <JavaScriptCore/JavaScriptCore.h>
    
    @protocol NSTestExport <JSExport>
    -(NSString *)str;
    -(void)setStr:(NSString *)str;
    @end
    
    @interface ViewController : UIViewController<NSTestExport>
    @property (nonatomic, strong) NSString *str;
    @end
    
    @implementation ViewController
    - (void)viewDidLoad {
        [super viewDidLoad];
        _str = @"asdf";
            
        context = [[JSContext alloc] init];
        
        context.exceptionHandler = ^(JSContext *context, JSValue *exception) {
            NSLog(@"exception: %@",exception);
        };
        
        context[@"log"] = ^(NSString *msg){
            NSLog(@"log msg: %@",msg);
        };
        
        context[@"viewController"] = self;
        
        [context evaluateScript:@"viewController.setStr('dsfg')"];
        JSValue *string = [context evaluateScript:@"viewController.str()"];
    
         NSLog(@"log str: %@",[result toString]);
    }
    

    但是这样的实现并不灵活,如果我有大量的类和其中的方法要在js中使用,那么我可能需要实现大量的JSExport协议,这样会导致项目中的代码量大大增加。于是想到了可以使用runtime动态创建这些协议,然后添加到class中。

    1、首先让我们制作一个扩展JSExport的新协议,假设我们有一个Class class我们要导出的变量:

    const char *protocolName = class_getName(class);
        Protocol *protocol = objc_allocateProtocol(protocolName);
        protocol_addProtocol(protocol, objc_getProtocol("JSExport"));
    

    2、然后我们从类中读取方法列表和属性列表,并将它们添加到protocol中:
    实例方法:

    {
        NSUInteger methodCount, classMethodCount;
        Method *methods, *classMethods;
        methods = class_copyMethodList(class, &methodCount);
        for (NSUInteger methodIndex = 0; methodIndex < methodCount; ++methodIndex) {
            Method method = methods[methodIndex];
            protocol_addMethodDescription(protocol, method_getName(method), method_getTypeEncoding(method), YES, YES);
        }
    }
    

    类方法:

    {
        classMethods = class_copyMethodList(object_getClass(class), &classMethodCount);
        for (NSUInteger methodIndex = 0; methodIndex < classMethodCount; ++methodIndex) {
            Method method = classMethods[methodIndex];
            protocol_addMethodDescription(protocol, method_getName(method), method_getTypeEncoding(method), YES, NO);
        }
    }
    
    

    属性:
    添加属性的方法基本和添加方法相同,但是我们还需要获取每个属性的特性,并添加到协议中

    {
        NSUInteger propertyCount;
        objc_property_t *properties;
        properties = class_copyPropertyList(class, &propertyCount);
        for (NSUInteger propertyIndex = 0; propertyIndex < propertyCount; ++propertyIndex) {
            objc_property_t property = properties[propertyIndex];
            NSUInteger attributeCount;
    //每个属性的特性
            objc_property_attribute_t *attributes = property_copyAttributeList(property, &attributeCount);
            protocol_addProperty(protocol, property_getName(property), attributes, attributeCount, YES, YES);
            free(attributes);
        }
    }
    

    3、将新协议添加到类中

    objc_registerProtocol(protocol);
    //校验protocol是否遵循JSExport协议
    BOOL conform = protocol_conformsToProtocol(protocol, @protocol(JSExport));
    NSLog(@"conform: %d",conform);
            
    BOOL success = class_addProtocol(class, protocol);
    

    4、然后理论上我们应该是可以在js中使用这个类中的方法了,接下来使用下面的代码测试下。

    context = [[JSContext alloc] init];
        
        context.exceptionHandler = ^(JSContext *context, JSValue *exception) {
            NSLog(@"exception: %@",exception);
        };
            
        context[@"viewController"] = self;
        
        [context evaluateScript:@"viewController.setStr('dsfg')"];
    
    

    然后我们发现,js的执行抛了异常。为什么呢?我们的实现逻辑并没有问题。
    这里查看JavaScriptCore源代码。

    最后发现原因在与objCCallbackFunctionForMethod方法,改函数通过调用objCCallbackFunctionForInvocation返回了一个原生函数的指针JSObjectRefobjCCallbackFunctionForInvocation函数的调用语句如下:

    objCCallbackFunctionForInvocation(context, invocation, isInstanceMethod ? CallbackInstanceMethod : CallbackClassMethod, isInstanceMethod ? cls : nil, _protocol_getMethodTypeEncoding(protocol, sel, YES, isInstanceMethod))。
    

    这里使用了_protocol_getMethodTypeEncoding函数。到ObjcRuntimeExtras.h中看看函数的定义。

    // Forward declare some Objective-C runtime internal methods that are not API.
    const char *_protocol_getMethodTypeEncoding(Protocol *, SEL, BOOL isRequiredMethod, BOOL isInstanceMethod);
    

    再到https://opensource.apple.com/source/objc4/objc4-551.1/runtime/objc-runtime-new.mm中找到了实现:

    /***********************************************************************
     * _protocol_getMethodTypeEncoding
     * Return the @encode string for the requested protocol method.
     * Returns nil if the compiler did not emit any extended @encode data.
     * Locking: acquires runtimeLock
     **********************************************************************/
    const char *
    _protocol_getMethodTypeEncoding(Protocol *proto_gen, SEL sel,
                                    BOOL isRequiredMethod, BOOL isInstanceMethod)
    {
        protocol_t *proto = newprotocol(proto_gen);
        if (!proto) return nil;
        fixupProtocolIfNeeded(proto);
        const char *enc;
        rwlock_read(&runtimeLock);
        enc = protocol_getMethodTypeEncoding_nolock(proto, sel,
                                                    isRequiredMethod,
                                                    isInstanceMethod);
        rwlock_unlock_read(&runtimeLock);
        return enc;
    }
    
    

    函数注释中写名了,Returns nil if the compiler did not emit any extended @encode data.所以我们只能在编译阶段创建好JSExport

    本文作者: ctinusdev
    原文链接: https://ctinusdev.github.io/2017/08/05/CantnotCreateJSExportAtRuntime/
    转载请注明出处!

    相关文章

      网友评论

          本文标题:为什么不能runtime创建JSExport类型的Protoco

          本文链接:https://www.haomeiwen.com/subject/wgnfdxtx.html