iOS GCD单例

    xiaoxiao2021-03-25  106

    单例模式可能是设计模式中最简单的形式了,这一模式的意图就是使得类中的一个对象成为系统中的唯一实例。它提供了对类的对象所提供的资源的全局访问点。因此需要用一种只允许生成对象类的唯一实例的机制。下面让我们来看下单例的作用:

    可以保证的程序运行过程,一个类只有一个示例,而且该实例易于供外界访问从而方便地控制了实例个数,并节约系统资源。

    下面我们利用GCD来新建一个单例类

    #import <Foundation/Foundation.h> @interface MZUserApplication : NSObject +(instancetype)shareInstance; - (BOOL)isAuthorized; @end #import "MZUserApplication.h" static id _instance; @implementation MZUserApplication +(instancetype)allocWithZone:(struct _NSZone *)zone{ static dispatch_once_t onceToken; dispatch_once(&onceToken,^{ _instance = [super allocWithZone:zone]; }); return _instance; } +(instancetype)shareInstance{ static dispatch_once_t onceToken; dispatch_once(&onceToken,^{ _instance = [[self alloc] init]; }); return _instance; } - (id)copyWithZone:(NSZone *)zone{ return _instance; } - (id)mutableCopyWithZone:(NSZone *)zone { return _instance; } -(BOOL)isAuthorized{ return [[NSUserDefaults standardUserDefaults]objectForKey:@"isLogin"]; } @end

    转载请注明原文地址: https://ju.6miu.com/read-20371.html

    最新回复(0)