美文网首页
iOS中单例的使用

iOS中单例的使用

作者: f1e583c455bf | 来源:发表于2017-05-02 14:46 被阅读0次

    一、单例的定义

    单例设计模式是一个类只有一个实例,有一个全局的接口来访问这个实例。

    单例设计模式可以用于需要被多次广泛或者说多次使用的资源中,比如我们常见的网络请求类、工具类以及其它管理类等。比如我iOS开发中常见的系统单例[UIApplication sharedApplication]、[NSUserDefaults standardUserDefaults]等。

    单例可以保证某个类在程序运行过程中最多只有一个实例,也就是对象实例只占用一份内存资源。

    二、单例的特点

    • 该类只有一个实例
    • 该类必须能够自行创建这个实例
    • 该类必须能够自行向整个系统提供这个实例

    三、单例的优缺点

    • 优点
    1. 提供了对唯一实例的受控访问。
    2. 由于在系统内存中只存在一个对象,因此可以节约系统资源,对于一些需要频繁创建和销毁的对象单例模式无疑可以提高系统的性能。
    3. 因为单例模式的类控制了实例化的过程,所以类可以更加灵活修改实例化过程。
    • 缺点
    1. 单例对象一旦建立,对象指针是保存在静态区的,单例对象在堆中分配的内存空间,会在应用程序终止后才会被释放。
    2. 单例类无法继承,因此很难进行类的扩展。
    3. 单例不适用于变化的对象,如果同一类型的对象总是要在不同的用例场景发生变化,单例就会引起数据的错误,不能保存彼此的状态。

    四、单例的使用

    创建单例类MySignletonClass
    MySignletonClass.h文件

    #import <Foundation/Foundation.h>
    @interface MySignletonClass : NSObject
    @property (nonatomic, copy) NSString *userName;
    //单例方法
    + (instancetype)sharedSingleton;
    @end
    

    MySignletonClass.m文件

    #import "MySignletonClass.h"
    @implementation MySignletonClass
    //全局变量
    static id _instance = nil;
    
    //单例方法
    + (instancetype)sharedSingleton{
        return [[self alloc] init];
    }
    //alloc会调用allocWithZone
    + (instancetype)allocWithZone:(struct _NSZone *)zone{
        //只进行一次
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            _instance = [super allocWithZone:zone];
        });
        return _instance;
    }
    //初始化方法
    - (instancetype)init{
        //只进行一次
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            _instance = [super init];
        });
        return _instance;
    }
    //copy在底层 会调用copyWithZone
    - (id)copyWithZone:(NSZone *)zone{
        return _instance;
    }
    + (id)copyWithZone:(struct _NSZone *)zone{
        return  _instance;
    }
    + (id)mutableCopyWithZone:(struct _NSZone *)zone{
        return _instance;
    }
    - (id)mutableCopyWithZone:(NSZone *)zone{
        return _instance;
    }
    

    例如登录后可给userName赋值

    [MySignletonClass sharedSingleton].userName = @"这里赋值";
    

    userName存在,使用uaserName

    [MySignletonClass sharedSingleton].userName
    

    相关文章

      网友评论

          本文标题:iOS中单例的使用

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