美文网首页
iOS单例模式

iOS单例模式

作者: 加盐白咖啡 | 来源:发表于2019-08-25 01:19 被阅读0次

Singleton.h

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface Singleton : NSObject
// 单例模式
+ (instancetype)shareSingleton;
@end

NS_ASSUME_NONNULL_END

Singleton.m

#import "Singleton.h"

@implementation Singleton
// 单例类的静态实例对象,因对象需要唯一性,故只能是static类型
static Singleton *_defaultManager = nil;
/**
   单例模式对外的唯一接口,用到的dispatch_once函数在一个应用程序内只会执行一次,且dispatch_once能确保线程安全
  */
+ (instancetype)shareSingleton {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (_defaultManager == nil) {
            _defaultManager = [[self allocWithZone:nil] init];
        }
    });
    return _defaultManager;
}
/**
   覆盖该方法主要确保当用户通过[[Singleton alloc] init]创建对象时对象的唯一性,alloc方法会调用该方法,只不过zone参数默认为nil,因该类覆盖了allocWithZone方法,所以只能通过其父类分配内存,即[super allocWithZone:zone]
*/
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _defaultManager = [super allocWithZone:zone];
    });
    return _defaultManager;
}

// 覆盖该方法主要确保当用户通过copy方法产生对象时对象的唯一性
- (nonnull id)copyWithZone:(nullable NSZone *)zone {
    return [[self class] shareSingleton];
}

// 覆盖该方法主要确保当用户通过mutableCopy方法产生对象时对象的唯一性
- (nonnull id)mutableCopyWithZone:(nullable NSZone *)zone {
    return [[self class] shareSingleton];
}

@end

相关文章

  • 单例

    iOS单例模式iOS之单例模式初探iOS单例详解

  • iOS 单例模式

    关于单例模式的详解,看完这几篇,就完全了然了。iOS 单例模式iOS中的单例模式iOS单例的写法

  • iOS 单例模式 or NSUserDefaults

    本文内容:iOS的单例模式NSUserDefaults的使用总结:iOS单例模式 and NSUserDefaul...

  • 单例模式 Singleton Pattern

    单例模式-菜鸟教程 iOS中的设计模式——单例(Singleton) iOS-单例模式写一次就够了 如何正确地写出...

  • 【设计模式】单例模式

    学习文章 iOS设计模式 - 单例 SwiftSingleton 原理图 说明 单例模式人人用过,严格的单例模式很...

  • iOS模式设计之--创建型:1、单例模式

    iOS模式设计之--1、单例模式

  • iOS单例模式容错处理

    ios 单例模式容错处理 1、单例模式的使用和问题解决 在ios开发的过程中,使用单例模式的场景非常多。系统也有很...

  • 谈一谈iOS单例模式

    这篇文章主要和大家谈一谈iOS中的单例模式,单例模式是一种常用的软件设计模式,想要深入了解iOS单例模式的朋友可以...

  • iOS知识梳理3:设计模式

    iOS有哪些常见的设计模式?单例模式/委托模式/观察者模式/MVC模式 单例模式 单例保证了应用程序的生命周期内仅...

  • 单例对象

    iOS单例模式(Singleton)单例模式的意思就是:只有一个实例;单例模式确保每个类只有一个实例,而且自行实例...

网友评论

      本文标题:iOS单例模式

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