• Working with Methods


    1. method_invoke

    Note: way to eliminate compiler warnning

            . ENABLE_STRICT_OBJC_MSGSEND = NO; 

            . int (*action)(id, SEL, int) = (int (*)(id, SEL, int)) objc_msgSend;

    Description:   Calls the implementation of a specified method.

    Declaration: id method_invoke(id receiver,Method m, ...) 

    Example:

    @interface KSModel4CheckMethod : NSObject
    
     + (void)classPrint;
     - (void)instancePrint;
     @end
    
     @implementation KSModel4CheckMethod
    
     #define PRINT_CMD NSLog(@"%@", NSStringFromSelector(_cmd))
    
     + (void)classPrint {
        PRINT_CMD;
    }
    
    - (void)instancePrint {
        PRINT_CMD;
    }
    @end
    
    #import <Foundation/Foundation.h>
    #import <objc/runtime.h>
    #import <objc/message.h>
    #import "KSModel4CheckMethod.h"
    
    void test_0_getName_NSString();
    
    int main(int argc, const char * argv[]) {
        @autoreleasepool {
            test_0_method_invoke();
        }
        return 0;
    }
    
    void test_0_method_invoke() {
    
        KSModel4CheckMethod *instance = [[KSModel4CheckMethod alloc] init];
        Class clazz = [KSModel4CheckMethod class];
        Method clazz_method = class_getClassMethod(clazz, @selector(classPrint));
        Method instance_method = class_getInstanceMethod(clazz, @selector(instancePrint));
    
    //    Method clazz_method = class_getClassMethod(clazz, @selector(instancePrint));
    //    Method instance_method = class_getInstanceMethod(clazz, @selector(classPrint));
    //    method_invoke(clazz, nil);
    //    method_invoke(instance, nil);
    
        method_invoke(clazz, clazz_method);
        method_invoke(clazz, instance_method);
        method_invoke(instance, clazz_method);
        method_invoke(instance, instance_method);
    }

    Result:

    1. method should be fetched from class

        class_getClassMethod(instance, @selector(instancePrint)) or 

        class_getInstanceMethod(instace, @selector(classPrint))  Return nil

    2. 2rd parameter with nil would lead to crash

        method_invoke(clazz, nil);

        method_invoke(instance, nil);

    3. 1rd parameter with instance or class  would produce same output

        method_invoke(clazz, clazz_method);

        method_invoke(clazz, instance_method);

        method_invoke(instance, clazz_method);

        method_invoke(instance, instance_method);

    Deepening:

    1.How do methods stored in logic and in physic 

     

  • 相关阅读:
    reids 入门
    关于字典的那些事儿.
    更新阿里源repo出的问题
    关于-编码进阶
    *** 数据类型之间的转化
    关于列表那些事:12.24
    while else 结构体(自测)
    关于切片的步长为正负值 的问题(自测)
    if 嵌套if 的先后顺序的区别 (自测)
    二: python基础数据类型(int,
  • 原文地址:https://www.cnblogs.com/hushuai-ios/p/5087465.html
Copyright © 2020-2023  润新知