YYClassInfo.h.m

/**
 Class information for a class.    
一个类的类信息模型
 */
@interface YYClassInfo : NSObject

///< class object   本类类对象
@property (nonatomic, assign, readonly) Class cls; 

///< super class object 父类类对象
@property (nullable, nonatomic, assign, readonly) Class superCls; 

///< class's meta class object  元类类对象
@property (nullable, nonatomic, assign, readonly) Class metaCls;  

///< whether this class is meta class   是否是一个元类
@property (nonatomic, readonly) BOOL isMeta; 

///< class name   类名
@property (nonatomic, strong, readonly) NSString *name; 

///< super class's class info  父类的类信息
@property (nullable, nonatomic, strong, readonly) YYClassInfo *superClassInfo; 

// 变量列表(数组)
@property (nullable, nonatomic, strong, readonly) NSDictionary<NSString *, YYClassIvarInfo *> *ivarInfos; ///< ivars

// 方法列表(数组)
@property (nullable, nonatomic, strong, readonly) NSDictionary<NSString *, YYClassMethodInfo *> *methodInfos; ///< methods

// 属性列表(数组)
@property (nullable, nonatomic, strong, readonly) NSDictionary<NSString *, YYClassPropertyInfo *> *propertyInfos; ///< properties

/**
 If the class is changed (for example: you add a method to this class with
 'class_addMethod()'), you should call this method to refresh the class info cache.
 如果这个类是改变了的(例如: 你通过调用 class_addMethod() 给这类添加了方法 ),你就需要调用这个方法来刷新类的缓存信息。
 
 After called this method, `needUpdate` will returns `YES`, and you should call 
 'classInfoWithClass' or 'classInfoWithClassName' to get the updated class info.
调用这个方法后, needUpdate 将返回 yes, 你将调用 classInfoWithClass 或者 classInfoWithClassName 来根系类信息。
 */
- (void)setNeedUpdate;

/**
 If this method returns `YES`, you should stop using this instance and call
 `classInfoWithClass` or `classInfoWithClassName` to get the updated class info.
如果这个方法返回 yes , 你需要停止使用这个类的实例并调用 classInfoWithClass 或  classInfoWithClassName 去更新类信息。
 
 @return Whether this class info need update.
 */
- (BOOL)needUpdate;

/**
 Get the class info of a specified Class.
 获取指定类的类信息。
 
 @discussion This method will cache the class info and super-class info
 at the first access to the Class. This method is thread-safe.
在第一次使用这个类的时候,这个方法将存储本类的类信息和父类的类信息。 这个方法是线程安全的。
 
 @param cls A class.
 @return A class info, or nil if an error occurs.  
 一个类的类信息,如果是 nil 就会发生一个错误。
 */
+ (nullable instancetype)classInfoWithClass:(Class)cls;


这个方法和上面的方法是一样的。
/**
 Get the class info of a specified Class.
 
 @discussion This method will cache the class info and super-class info
 at the first access to the Class. This method is thread-safe.
 
 @param className A class name.
 @return A class info, or nil if an error occurs.
 */
+ (nullable instancetype)classInfoWithClassName:(NSString *)className;
@implementation YYClassInfo {

    // 是否需要更新类信息
    BOOL _needUpdate;
}

- (instancetype)initWithClass:(Class)cls {

    // cls 为 nil 就直接返回 nil
    if (!cls) return nil;

    // 初始化父类
    self = [super init];
    
    // 记录 “类”
    _cls = cls;

    // 记录“父类”
    _superCls = class_getSuperclass(cls);

    // 判断是否是 "元" 类
    /*
      判断是一个 元类,主要是要确定是一个 “类“ 不是一个 ”实例“
      */ 
    _isMeta = class_isMetaClass(cls);

    // 不是 “元” 类
    if (!_isMeta) {

      // 获取当前类的 “元” 类
        _metaCls = objc_getMetaClass(class_getName(cls));
    }

    // 获取类名
    _name = NSStringFromClass(cls);

    // 调用 update 方法
    [self _update];

    // 获取父类的类信息
    _superClassInfo = [self.class classInfoWithClass:_superCls];
    return self;
}

- (void)_update {
    _ivarInfos = nil;
    _methodInfos = nil;
    _propertyInfos = nil;
    

    // 实例一个 "类" 制作
    Class cls = self.cls;

    // 定义变量记录方法的个数
    unsigned int methodCount = 0;

    // 获取方法列表信息
    Method *methods = class_copyMethodList(cls, &methodCount);
    if (methods) {

        // 获取方法信息
        NSMutableDictionary *methodInfos = [NSMutableDictionary new];
        _methodInfos = methodInfos;

        for (unsigned int i = 0; i < methodCount; i++) {
            YYClassMethodInfo *info = [[YYClassMethodInfo alloc] initWithMethod:methods[i]];
            if (info.name) methodInfos[info.name] = info;
        }
        free(methods);
    }


    // 获取属性列表信息
    unsigned int propertyCount = 0;
    objc_property_t *properties = class_copyPropertyList(cls, &propertyCount);
    if (properties) {
        NSMutableDictionary *propertyInfos = [NSMutableDictionary new];
        _propertyInfos = propertyInfos;
        for (unsigned int i = 0; i < propertyCount; i++) {
            YYClassPropertyInfo *info = [[YYClassPropertyInfo alloc] initWithProperty:properties[i]];
            if (info.name) propertyInfos[info.name] = info;
        }
        free(properties);
    }
    

    // 获取变量信息
    unsigned int ivarCount = 0;
    Ivar *ivars = class_copyIvarList(cls, &ivarCount);
    if (ivars) {
        NSMutableDictionary *ivarInfos = [NSMutableDictionary new];
        _ivarInfos = ivarInfos;
        for (unsigned int i = 0; i < ivarCount; i++) {
            YYClassIvarInfo *info = [[YYClassIvarInfo alloc] initWithIvar:ivars[i]];
            if (info.name) ivarInfos[info.name] = info;
        }
        free(ivars);
    }
    

    // 当获取的方法列表信息,属性列表信息,变量列表信息为空的时候对相应的存储变量置空
    if (!_ivarInfos) _ivarInfos = @{};
    if (!_methodInfos) _methodInfos = @{};
    if (!_propertyInfos) _propertyInfos = @{};
    
    // 更新是否更新的标记
    _needUpdate = NO;
}

- (void)setNeedUpdate {
    _needUpdate = YES;
}

- (BOOL)needUpdate {
    return _needUpdate;
}


// 一个类方法
+ (instancetype)classInfoWithClass:(Class)cls {
    // 判断类是否有值
    if (!cls) return nil;


    // 缓存池用的是全局静态变量
    // 类缓存池
    static CFMutableDictionaryRef classCache;
    // 元类缓存池
    static CFMutableDictionaryRef metaCache;

    // 锁
    static dispatch_once_t onceToken;
    static dispatch_semaphore_t lock;

    // 类缓存池,和 元类缓存池保证只初始化一次
    dispatch_once(&onceToken, ^{
        classCache = CFDictionaryCreateMutable(CFAllocatorGetDefault(), 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
        metaCache = CFDictionaryCreateMutable(CFAllocatorGetDefault(), 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
        lock = dispatch_semaphore_create(1);
    });
    dispatch_semaphore_wait(lock, DISPATCH_TIME_FOREVER);

    // 获取缓存中的信息
    YYClassInfo *info = CFDictionaryGetValue(class_isMetaClass(cls) ? metaCache : classCache, (__bridge const void *)(cls));
    if (info && info->_needUpdate) {
        [info _update];
    }
    dispatch_semaphore_signal(lock);

    // 没有从缓存池中获取信息直接实例化一个
    if (!info) {
        info = [[YYClassInfo alloc] initWithClass:cls];
        if (info) {
            dispatch_semaphore_wait(lock, DISPATCH_TIME_FOREVER);

            // 将信息保存到缓存池中
            CFDictionarySetValue(info.isMeta ? metaCache : classCache, (__bridge const void *)(cls), (__bridge const void *)(info));
            dispatch_semaphore_signal(lock);
        }
    }
    return info;
}

+ (instancetype)classInfoWithClassName:(NSString *)className {

    // 通过字符串实例化一个类
    Class cls = NSClassFromString(className);
    return [self classInfoWithClass:cls];
}

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

推荐阅读更多精彩内容