YYClassMethodInfo.h.m

作者: Laughingg | 来源:发表于2016-07-28 17:00 被阅读5次
    /**
     Method information.
     */
    @interface YYClassMethodInfo : NSObject
    @property (nonatomic, assign, readonly) Method method;                  ///< method opaque struct
    @property (nonatomic, strong, readonly) NSString *name;                 ///< method name
    @property (nonatomic, assign, readonly) SEL sel;                        ///< method's selector
    @property (nonatomic, assign, readonly) IMP imp;                        ///< method's implementation
    @property (nonatomic, strong, readonly) NSString *typeEncoding;         ///< method's parameter and return types
    @property (nonatomic, strong, readonly) NSString *returnTypeEncoding;   ///< return value's type
    @property (nullable, nonatomic, strong, readonly) NSArray<NSString *> *argumentTypeEncodings; ///< array of arguments' type
    
    /**
     Creates and returns a method info object.
     创建和返回一个方法信息模型对象
     
     @param method method opaque struct
     @return A new object, or nil if an error occurs.
     */
    - (instancetype)initWithMethod:(Method)method;
    @end
    
    @implementation YYClassMethodInfo
    
    - (instancetype)initWithMethod:(Method)method {
    
        // 方法结构体为 nil , 直接返回 nil
        if (!method) return nil;
    
        // 初始化对象
        self = [super init];
    
        // 记录传入的方法
        _method = method;
    
        // 获取方法的声明
        _sel = method_getName(method);
    
        // 获取方法的实现
        _imp = method_getImplementation(method);
    
        // 获取方法的名称
        const char *name = sel_getName(_sel);
        if (name) {
            _name = [NSString stringWithUTF8String:name];
        }
    
    
        // 参数和返回值
        const char *typeEncoding = method_getTypeEncoding(method);
        if (typeEncoding) {
            _typeEncoding = [NSString stringWithUTF8String:typeEncoding];
        }
    
        // 返回值的类型
        char *returnType = method_copyReturnType(method);
        if (returnType) {
            _returnTypeEncoding = [NSString stringWithUTF8String:returnType];
            free(returnType);
        }
    
        // 获取参数的个数 去获取参数的类型
        unsigned int argumentCount = method_getNumberOfArguments(method);
        if (argumentCount > 0) {
            NSMutableArray *argumentTypes = [NSMutableArray new];
            for (unsigned int i = 0; i < argumentCount; i++) {
                char *argumentType = method_copyArgumentType(method, i);
                NSString *type = argumentType ? [NSString stringWithUTF8String:argumentType] : nil;
                [argumentTypes addObject:type ? type : @""];
                if (argumentType) free(argumentType);
            }
            _argumentTypeEncodings = argumentTypes;
        }
        return self;
    }
    
    @end
    

    相关文章

      网友评论

        本文标题:YYClassMethodInfo.h.m

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