• 看完MJ讲解的单例后的个人总结


    1、单例的介绍

    单例是iOS常用的开发模式的一种。

    2、什么是单例

    单例就是一个类只创建一个对象,只分配一次内存空间。

    3、单例的应用场景

    1)系统的单例:  [UIApplication sharedApplication];

    2)应用中的单例:qq的背景图等

    4、单例的注意事项

    1)永远只分配一块内存来创建对象

    2)提供一个类方法,返回内部唯一的一个对象(一个实例)

    3)最好保证init方法也只初始化一次

    5、单例的创建

    1)重写分配内存方法

    //重写分配内存的方法
    + (instancetype)allocWithZone:(struct _NSZone *)zone
    {
        static dispatch_once_t once_Token;
        dispatch_once(&once_Token, ^{
            //保证只分配一次内存
            _instance = [super allocWithZone:zone];
            
        });
        return _instance;
        
    }

    2)创建类方法

    //创建share方法
    + (instancetype)sharePerson
    {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
           //只被init一次
            _instance = [[self alloc]init];
            
        });
        return _instance;
    }

    3)重写init方法

    - (instancetype)init
    {
        if (self = [super init]) {
            static dispatch_once_t onceToken;
            dispatch_once(&onceToken, ^{
                //赋值,初始化资源
            });
            
        }
        return self;
    }

    6、单例的调用和输出结果

    1)单例的调用

    Person * mark = [Person sharePerson];
        Person * mary = [[Person alloc]init];
        NSLog(@"mark ---%p  mary----  %p ",mark,mary);
    

     2)单例的输出结果

    2016-03-02 21:38:30.743 Single[2104:190961] mark ---0x7fe6325488e0  mary----  0x7fe6325488e0 
    
  • 相关阅读:
    mac 使用brew 安装php-redis
    thinkphp6 使用redis 实现消息队列
    Redis 桌面管理器:Another Redis Desktop Manager
    linux 查看并关闭shell脚本执行
    MySQL教程之concat以及group_concat的用法
    PHP redis 使用
    thinkphp6 command(自定义指令)
    git 使用
    linux shell中 "2>&1"含义
    linux crontab 定时任务
  • 原文地址:https://www.cnblogs.com/fengzhihao/p/5236660.html
Copyright © 2020-2023  润新知