如何优雅地清空单例的属性值

1.有漏洞的写法

- (void)rfClearPropertyValue {
        //1.存储属性的个数
        unsigned int propertyCount = 0;
        // 2.通过运行时获取当前类的所有属性
        objc_property_t *properties = class_copyPropertyList([self class], &propertyCount);
        // 3.遍历属性
        for (int i = 0; i < propertyCount; i ++) {
            objc_property_t property = properties[i];
            NSString *propertyName = [NSString stringWithFormat:@"%s", property_getName(property)];
            // 4.利用KVC 设置属性nil
            [self setValue:nil forKey:propertyName];
        }
        // 释放指针
        free(properties);
}

如果你的运气足够好,单例中所有的属性都是非基础类型,那么这么写是可以的,但是如果属性中有基础类型属性的时候(例如,int NSInterger),那么你会看到运行奔溃提示:could not set nil as the value for the key

2.升级版写法

- (void)clearPropertyValue {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        unsigned int propertyCount = 0;
        // 2.通过运行时获取当前类的所有属性
        objc_property_t *properties = class_copyPropertyList([self class], &propertyCount);
        // 3.遍历属性
        for (int i = 0; i < propertyCount; i ++) {
            objc_property_t property = properties[i];
            NSString *propertyName = [NSString stringWithFormat:@"%s", property_getName(property)];
            // 4.利用KVC 设置属性nil
            @try {
                [self setValue:nil forKey:propertyName];
            } @catch (NSException *exception) {
                [self setValue:@0 forKey:propertyName];
            } @finally {
                //
            }
        }
        // 释放指针
        free(properties);
    });//此处使用在子线程中实现重置单例属性的写法,因为在block中使用此方法时有死锁的情况;
}

*注:本文内容来自于简述作者:@yannChee, 本文章只是在原作者写法上把开辟子线程的写法调整到方法内部,原文:<<利用Runtime清空单例属性>>

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 用两张图告诉你,为什么你的 App 会卡顿? - Android - 掘金 Cover 有什么料? 从这篇文章中你...
    hw1212阅读 14,553评论 2 59
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 177,041评论 25 709
  • 1、很想实现多年夙愿:在成都买别墅或花园洋房,让梦想照进现实! 2、舍得花时间给自己:健身、读书、精进摄影、培养兴...
    我是德容阅读 1,189评论 0 0
  • 第一章:校园纷争 作者:风七栩,蝶梦雪冉 ...
    风七栩阅读 2,515评论 0 0

友情链接更多精彩内容