类型编码解析之YYModel

引例

假设有这么一个类

@protocol JKTestProtocol
- (void)just4Test;
@end

@interface ViewController ()
@property (nonatomic, strong) NSObject *test;
@end

如何动态获取ViewController中的property不用多说,直接利用runtime来做。同样,获取property的类型及修饰符也是通过runtime搞定(类型对应Objective-C type encodings,修饰符对应property type encodings,这就是所谓的类型编码)

熟悉这些知识点的童鞋,可以跳过引例直接阅读正文部分的YYModel类型编码解析

先上代码

- (void)viewDidLoad {
    [super viewDidLoad];
    
    objc_property_t property = class_getProperty([self class], "test");
    NSLog(@"property name:%s", property_getName(property));
    unsigned int outCount = 0;
    objc_property_attribute_t *attrs = property_copyAttributeList(property, &outCount);
    for (unsigned int i = 0; i < outCount; i++) {
        NSLog(@"attribute name:%s  attribute value:%s", attrs[i].name, attrs[i].value);
    }
    free(attrs);
}

说明:由于ViewController中只有一个属性,这里使用class_getProperty,一般使用class_copyPropertyList获取属性列表

控制台输出如下:


console

objc_property_attribute_t是什么:

/// Defines a property attribute
typedef struct {
    const char * _Nonnull name;           /**< The name of the attribute */
    const char * _Nonnull value;          /**< The value of the attribute (usually empty) */
} objc_property_attribute_t;

一个最简单的结构体,内部存着两个字符串,value后的注释写着usually empty。通过console可以看到,name为TV时,value有值,其余为空(事实上,T对应的value一定有之,G、S、V对应的value可能有值,其余对应的value都没值)

console中attribute name 就是property type encodings。T、&、N、V具体表示什么?戳这里查看官方文档

简单解读:
T打头,以V结尾。T对应的value中以字符串形式存着属性类型和遵守的协议,V对应的value如果有值,以字符串形式存着ivar。回到声明

@interface ViewController ()
@property (nonatomic, strong) NSObject *test;
@end

文档中,&对应retain,这里是strong(ARC与MRC历史遗留),N对应nonatomic,这里也是nonatomic。OK都能对得上

如何获取property的类型?最先想到的可能是@encode(<#type-name#>),type-name可以直接从T对应的value中截取,那么@encode又是如何工作的?

Objective-C中提供了另一套编码Type Encodings 戳这里查看官方文档

from Objective-C Runtime Programming Guide

注意:可以看到文档中说明,@encode不支持long double类型,long double与double类型编码后的结果都是d

所以,想获取long double类型还需自定义。YYModel将long double 类型编码自定义为D

 case 'D': return YYEncodingTypeLongDouble | qualifier;

有了以上知识储备,YYModel源码走你

正文

了解runtime的童鞋应该都知道Objective-C底层是一堆结构体,通过自定义结构体封装Class,结构体内部再包含其他结构体,诸如此类

#if !__OBJC2__
    Class _Nullable super_class                              OBJC2_UNAVAILABLE;
    const char * _Nonnull name                               OBJC2_UNAVAILABLE;
    long version                                             OBJC2_UNAVAILABLE;
    long info                                                OBJC2_UNAVAILABLE;
    long instance_size                                       OBJC2_UNAVAILABLE;
    struct objc_ivar_list * _Nullable ivars                  OBJC2_UNAVAILABLE;
    struct objc_method_list * _Nullable * _Nullable methodLists                    OBJC2_UNAVAILABLE;
    struct objc_cache * _Nonnull cache                       OBJC2_UNAVAILABLE;
    struct objc_protocol_list * _Nullable protocols          OBJC2_UNAVAILABLE;
#endif

} OBJC2_UNAVAILABLE;
/* Use `Class` instead of `struct objc_class *` */

#endif

这里不做进一步数据结构分析,只是借此和YYModel做简单对比。为了更好的OOP,YYModel将Objective-C底层结构体包含的信息以NSObject为基类重新构建成类,在这些重定义类的基础上获取信息

源码伺候(含注释)


@implementation YYClassPropertyInfo

- (instancetype)initWithProperty:(objc_property_t)property {
    if (!property) return nil;
    self = [super init];
    _property = property;
    const char *name = property_getName(property);
    if (name) {
        _name = [NSString stringWithUTF8String:name];
    }
    
    YYEncodingType type = 0;
    unsigned int attrCount;
//  获取property属性列表
    objc_property_attribute_t *attrs = property_copyAttributeList(property, &attrCount);
    for (unsigned int i = 0; i < attrCount; i++) {
        switch (attrs[i].name[0]) {
            case 'T': { // Type encoding
                if (attrs[i].value) {
                    _typeEncoding = [NSString stringWithUTF8String:attrs[i].value];
//  获取编码类型(后文会有这个函数)
                    type = YYEncodingGetType(attrs[i].value);
                    
                    if ((type & YYEncodingTypeMask) == YYEncodingTypeObject && _typeEncoding.length) {
                        NSScanner *scanner = [NSScanner scannerWithString:_typeEncoding];

//  扫描scanner string中的  @\   将字符串定位到  @\  后一个字符 
//  此时 scanLocation = 2
                        if (![scanner scanString:@"@\"" intoString:NULL]) continue;
                        
                        NSString *clsName = nil;
//  扫描之后字符串中  "  或者  <  字符,将截取的字符串存入clsName中,将字符串定位到 "  或者 < 后一个字符
//  因为string 不确定属性是否遵守某协议,所以可能还有 < ,如@"NSObject",也可能不含  <  ,如@"NSObject"
                        if ([scanner scanUpToCharactersFromSet: [NSCharacterSet characterSetWithCharactersInString:@"\"<"] intoString:&clsName]) {
                            if (clsName.length) _cls = objc_getClass(clsName.UTF8String);
                        }
                        
                        NSMutableArray *protocols = nil;
//  扫描之后字符串 中的 <  ,将字符串定位到 < 后一个字符
//  属性有可能遵循多个协议,包含多个 < ,如@"NSObject",所以此处用while循环
                        while ([scanner scanString:@"<" intoString:NULL]) {
                            NSString* protocol = nil;
//  扫描之后字符串中 < ,将截取的字符串存入protocol中,如@"NSObject",此时刚好截取到 JKTestProtocol
                            if ([scanner scanUpToString:@">" intoString: &protocol]) {
                                if (protocol.length) {
                                    if (!protocols) protocols = [NSMutableArray new];
                                    [protocols addObject:protocol];
                                }
                            }
//  扫描之后字符串中  >  ,将字符串定位到  >  后一个字符
                            [scanner scanString:@">" intoString:NULL];
                        }
                        _protocols = protocols;
                    }
                }
            } break;
//  ivar
            case 'V': { // Instance variable
//  如果value有值回去ivar的name
                if (attrs[i].value) {
                    _ivarName = [NSString stringWithUTF8String:attrs[i].value];
                }
            } break;
            case 'R': {
                type |= YYEncodingTypePropertyReadonly;
            } break;
            case 'C': {
                type |= YYEncodingTypePropertyCopy;
            } break;
            case '&': {
                type |= YYEncodingTypePropertyRetain;
            } break;
            case 'N': {
                type |= YYEncodingTypePropertyNonatomic;
            } break;
            case 'D': {
                type |= YYEncodingTypePropertyDynamic;
            } break;
            case 'W': {
                type |= YYEncodingTypePropertyWeak;
            } break;
//  自定义属性getter
            case 'G': {
                type |= YYEncodingTypePropertyCustomGetter;
                if (attrs[i].value) {
                    _getter = NSSelectorFromString([NSString stringWithUTF8String:attrs[i].value]);
                }
            } break;
//  自定义属性setter
            case 'S': {
                type |= YYEncodingTypePropertyCustomSetter;
                if (attrs[i].value) {
                    _setter = NSSelectorFromString([NSString stringWithUTF8String:attrs[i].value]);
                }
            } // break; commented for code coverage in next line
            default: break;
        }
    }
    if (attrs) {
        free(attrs);
        attrs = NULL;
    }
    
    _type = type;
    if (_name.length) {
//  如果没有自定义getter,获取getter的name
        if (!_getter) {
            _getter = NSSelectorFromString(_name);
        }
//  如果没有自定义setter,获取setter的name
        if (!_setter) {
            _setter = NSSelectorFromString([NSString stringWithFormat:@"set%@%@:", [_name substringToIndex:1].uppercaseString, [_name substringFromIndex:1]]);
        }
    }
    return self;
}

@end

从源码来看,initWithProperty:无非是在通过attribute做字符串的截取,然后放到YYClassPropertyInfo生成对象对应的属性中

再看另一个关键函数YYEncodingGetType

YYEncodingType YYEncodingGetType(const char *typeEncoding) {
    char *type = (char *)typeEncoding;
    if (!type) return YYEncodingTypeUnknown;
    size_t len = strlen(type);
    if (len == 0) return YYEncodingTypeUnknown;
    
    YYEncodingType qualifier = 0;
    bool prefix = true;
//  获取method编码类型
//  可能不止一个字符,所以通过while循环、"++"操作,来移动指针指向
    while (prefix) {
        switch (*type) {
            case 'r': {
                qualifier |= YYEncodingTypeQualifierConst;
                type++;
            } break;
            case 'n': {
                qualifier |= YYEncodingTypeQualifierIn;
                type++;
            } break;
            case 'N': {
                qualifier |= YYEncodingTypeQualifierInout;
                type++;
            } break;
            case 'o': {
                qualifier |= YYEncodingTypeQualifierOut;
                type++;
            } break;
            case 'O': {
                qualifier |= YYEncodingTypeQualifierBycopy;
                type++;
            } break;
            case 'R': {
                qualifier |= YYEncodingTypeQualifierByref;
                type++;
            } break;
            case 'V': {
                qualifier |= YYEncodingTypeQualifierOneway;
                type++;
            } break;
            default: { prefix = false; } break;
        }
    }

    len = strlen(type);
    if (len == 0) return YYEncodingTypeUnknown | qualifier;

//  获取object编码类型
    switch (*type) {
        case 'v': return YYEncodingTypeVoid | qualifier;
        case 'B': return YYEncodingTypeBool | qualifier;
        case 'c': return YYEncodingTypeInt8 | qualifier;
        case 'C': return YYEncodingTypeUInt8 | qualifier;
        case 's': return YYEncodingTypeInt16 | qualifier;
        case 'S': return YYEncodingTypeUInt16 | qualifier;
        case 'i': return YYEncodingTypeInt32 | qualifier;
        case 'I': return YYEncodingTypeUInt32 | qualifier;
        case 'l': return YYEncodingTypeInt32 | qualifier;
        case 'L': return YYEncodingTypeUInt32 | qualifier;
        case 'q': return YYEncodingTypeInt64 | qualifier;
        case 'Q': return YYEncodingTypeUInt64 | qualifier;
        case 'f': return YYEncodingTypeFloat | qualifier;
        case 'd': return YYEncodingTypeDouble | qualifier;
        case 'D': return YYEncodingTypeLongDouble | qualifier;
        case '#': return YYEncodingTypeClass | qualifier;
        case ':': return YYEncodingTypeSEL | qualifier;
        case '*': return YYEncodingTypeCString | qualifier;
        case '^': return YYEncodingTypePointer | qualifier;
        case '[': return YYEncodingTypeCArray | qualifier;
        case '(': return YYEncodingTypeUnion | qualifier;
        case '{': return YYEncodingTypeStruct | qualifier;
        case '@': {
            if (len == 2 && *(type + 1) == '?')
                return YYEncodingTypeBlock | qualifier;
            else
                return YYEncodingTypeObject | qualifier;
        }
        default: return YYEncodingTypeUnknown | qualifier;
    }
}

YYEncodingGetType其实就是获取method和object的编码类型

最后再看YYEncodingType是如何定义的

typedef NS_OPTIONS(NSUInteger, YYEncodingType) {
    YYEncodingTypeMask       = 0xFF, ///< mask of type value
    YYEncodingTypeUnknown    = 0, ///< unknown
// ...此处省略多种类型
    YYEncodingTypeCArray     = 22, ///< char[10] (for example)
    
    YYEncodingTypeQualifierMask   = 0xFF00,   ///< mask of qualifier
    YYEncodingTypeQualifierConst  = 1 << 8,  ///< const
// ...此处省略多种类型
    YYEncodingTypeQualifierOneway = 1 << 14, ///< oneway
    
    YYEncodingTypePropertyMask         = 0xFF0000, ///< mask of property
    YYEncodingTypePropertyReadonly     = 1 << 16, ///< readonly
// ...此处省略多种类型
    YYEncodingTypePropertyDynamic      = 1 << 23, ///< @dynamic
};

很简单,C语言的基础知识,通过Mask做与或运算即可得到定义的类型

通过Type Encoding可以做一些crazy things,毕竟越接近底层自由度就越大

你可能感兴趣的:(类型编码解析之YYModel)