美文网首页
单例里你不知道的事儿

单例里你不知道的事儿

作者: 内心戏十足的伪胖子 | 来源:发表于2018-08-15 15:53 被阅读80次

    一位开发前辈玉令天下的博客里对单例的介绍很不错,原文iOS的单例模式在这里作两点补充。

    • 即使用GCD的dispatch_once 创建的单例,最好还是遵循<NSCopying,NSMutableCopying>的协议,并实现相应的方法,防止别人误调copy方法而崩溃

    在这里我写了个demo
    Singleton.h文件如下

    #import <Foundation/Foundation.h>
    
    @interface Singleton : NSObject
    
    +(instancetype) shareInstance;
    
    @property (copy, nonatomic) NSString *name;
    @property (copy, nonatomic) NSString *title;
    
    @end
    

    Singleton.m文件如下

    #import "Singleton.h"
    
    @interface Singleton () <NSCopying,NSMutableCopying>
    
    @end
    
    @implementation Singleton
    
    static Singleton* _instance = nil;
    
    +(instancetype) shareInstance {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            _instance = [[super allocWithZone:NULL] init];//调用[[super allocWithZone:NULL] init],因为本类已经重载allocWithZone基本的对象分配方法,要借用父类(NSObject)的功能来帮助处理底层内存分配
            _instance.name = @"";
            _instance.title = @"";
        });
        
        return _instance;
    }
    
    +(id)allocWithZone:(struct _NSZone *)zone {
    //    return [Singleton shareInstance];
        return _instance;//两种写法效果是一样的
    }
    
    - (id)copyWithZone:(nullable NSZone *)zone {
    //    return [Singleton shareInstance];
        return _instance;
    }
    
    - (id)mutableCopyWithZone:(nullable NSZone *)zone {
    //    return [Singleton shareInstance];
        return _instance;
    }
    
    - (NSString *)description {
        return [NSString stringWithFormat:@"_name====%@,_title=====%@",_name,_title];
    }
    

    测试方法如下

    - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
        Singleton *singleton = [Singleton shareInstance];
        singleton.name = @"singleton";
        singleton.title = @"singletonDesc";
        NSLog(@"singleton------%p,description------%@",singleton,singleton);
        
        Singleton *singletonCopy = [singleton copy];
        NSLog(@"singletonCopy------%p,description------%@",singletonCopy,singletonCopy);
        
        Singleton *singletonMutableCopy = [singleton mutableCopy];
        NSLog(@"singletonMutableCopy------%p,description------%@",singletonMutableCopy,singletonMutableCopy);
        
        Singleton *singletonShareInstanceAgain = [Singleton shareInstance];
        NSLog(@"singletonShareInstanceAgain------%p,singletonShareInstanceAgain------%@",singletonShareInstanceAgain,singletonShareInstanceAgain);
    
        Singleton *singletonAlloc = [[Singleton alloc] init];
        NSLog(@"singletonAlloc------%p,description------%@",singletonAlloc,singletonAlloc);
    }
    

    打印结果如下

    2018-08-15 15:00:31.441223+0800 SingletonTest[65282:7781841] singleton------0x60400042c800,description------_name====singleton,_title=====singletonDesc
    2018-08-15 15:00:31.441499+0800 SingletonTest[65282:7781841] singletonCopy------0x60400042c800,description------_name====singleton,_title=====singletonDesc
    2018-08-15 15:00:31.441726+0800 SingletonTest[65282:7781841] singletonMutableCopy------0x60400042c800,description------_name====singleton,_title=====singletonDesc
    2018-08-15 15:00:31.441855+0800 SingletonTest[65282:7781841] singletonShareInstanceAgain------0x60400042c800,singletonShareInstanceAgain------_name====singleton,_title=====singletonDesc
    2018-08-15 15:00:31.442457+0800 SingletonTest[65282:7781841] singletonAlloc------0x60400042c800,description------_name====singleton,_title=====singletonDesc

    可以看出shareInstance、copy、mutableCopy、alloc创建出来是同一个单例,内存地址相同

    • 单例对象的释放:在所有使用该单例的对象都释放后,单例对象本身也会自己释放 原文地址
    +(instancetype)shareInstance {
        static __weak SingletonClass *instance;
        SingletonClass *strongInstance = instance;
        @synchronized(self) {
            if (strongInstance == nil) {
                strongInstance = [[[self class] alloc] init];
                instance = strongInstance;
            }
        }
        return strongInstance;
    }
    

    写了个demo验证了,这样创建的单例确实会随着持有对象的销毁而销毁

    2018-08-15 15:45:26.197552+0800 SingletonTest[65879:7837310] instanceAddress=0x600000000ef0,_content====the VC Hold Instance
    2018-08-15 15:45:28.625037+0800 SingletonTest[65879:7837310] instanceAddress=0x600000000f10,_content====the Instance after VC dealloc Information

    大概的思路是,从A控制器进入B控制器,B控制器创建一个单例,打印此单例的信息,然后B控制器回到A控制器,在A控制器创建单例并打印单例的信息,两次打印的信息对比地址不同。

    如果有错误的地方,欢迎指正。

    相关文章

      网友评论

          本文标题:单例里你不知道的事儿

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