美文网首页
iOS单例模式

iOS单例模式

作者: _叫我小贱 | 来源:发表于2016-07-02 18:10 被阅读32次
  • 单例模式可以保证在程序运行的过程中,一个类只存在一个对象,而且该实例易于供外界访问。这个对象只有在该程序运行结束后才会销毁。

  • 因为只存在一个对象,所以我们保证每次调用alloc生成的对象是同一块地址即可,但是使用alloc的时候,alloc会调用其父类的allocwithzone方法分配内存,所以我们要重写allocwithzone方法

  • 实现单例模式有两种方法。

方法1:GCD方式实现

1.allocwithzone方法的重写

static Person *_person;

+(instancetype)allocWithZone:(struct _NSZone *)zone
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _person = [super allocWithZone:zone];
    });
    return _person;
}

2.实现单例的shared方法

+ (instancetype)sharedPerson
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _person = [[self alloc] init];
    });
    return _person;
}

3.重写copy方法

@interface Person() <NSCopying>

@end

- (id)copyWithZone:(NSZone *)zone
{
    return _person;
}

方法二:加锁实现

1.allocwithzone方法的重写

static Person *_person;

+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
    @synchronized (self) {
        if (_person == nil) {
            _person = [super allocWithZone:zone];
        }
    }
    return _person;
}

2.实现单例的shared方法

+ (instancetype)sharedPerson
{
    @synchronized (self) {
        if (_person == nil) {
            _person = [[self alloc] init];
        }
    }
    return _person;
}

3.重写copy方法

@interface Person() <NSCopying>

@end

- (id)copyWithZone:(NSZone *)zone
{
    return _person;
}

相关文章

  • 单例

    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/spmqjttx.html