美文网首页selector
iOS单例模式的写法

iOS单例模式的写法

作者: 凌巅 | 来源:发表于2016-04-19 16:58 被阅读864次

iOS单例模式的写法

1、第一种

static AccountManager *DefaultManager = nil;

+ (AccountManager *)sharedManager {
    if (!DefaultManager) {
        DefaultManager = [[self allocWithZone:NULL] init];
        return DefaultManager;
    }
 }

这种写法很普通,就是设置一个对象类型的静态变量,判断这个变量是否为nil,来创建相应的对象

2.第二种

iOS4.0之后,官方推荐了另一种写法:

+(AccountManager *)sharedManager{
    static AccountManager *defaultManager = nil;
    disptch_once_t once;
    disptch_once(&once,^{
        defaultManager = [[self alloc] init];
        }
    )
    return defaultManager;
}

第二种写法有几点好处:
1.线程安全
2.满足静态分析器的要求
3.兼容了ARC

根据苹果文档的介绍

dispatch_once

Executes a block object once and only once for the lifetime of an application.

void dispatch_once(
dispatch_once_t *predicate,
dispatch_block_t block);

Parameters

predicate

A pointer to a dispatch_once_t structure that is used to test whether the block has completed or not.

block

The block object to execute once.

Discussion

This function is useful for initialization of global data (singletons) in an application. Always call this function before using or testing any variables that are initialized by the block.

If called simultaneously from multiple threads, this function waits synchronously until the block has completed.

The predicate must point to a variable stored in global or static scope. The result of using a predicate with automatic or dynamic storage is undefined.

Availability

Available in iOS 4.0 and later.

Declared In

dispatch/once.h

#######从文档中我们可以看到,该方法的主要作用就是在程序运行期间,仅执行一次block对象。所以说很适合用来生成单例对象,其实任何只需要执行一次的代码我们都可以使用这个函数。

相关文章

  • iOS 单例模式

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

  • 单例的2种写法

    单例模式是iOS开发中最常用的设计模式,iOS的单例模式有两种官方写法,如下: 1,常用写法 import "Se...

  • iOS-两种单例模式的实现

    单例模式是开发中最常用的写法之一,创建一个单例很多办法,iOS的单例模式有两种官方写法,如下: 不使用GCD 某些...

  • 设计模式之单例模式详解

    设计模式之单例模式详解 单例模式写法大全,也许有你不知道的写法 导航 引言 什么是单例? 单例模式作用 单例模式的...

  • 单例

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

  • 第03条 用私有构造方法或者枚举类型强化Singleton属性

    单例模式最佳写法1 - 双重校验锁 单例模式最佳写法2 - 静态内部类

  • 单例模式

    单例模式的写法

  • Kotlin中的单例模式与Java对比

    目前java中的单例模式有多种写法,kotlin中的写法更多一点,本篇会总结全部的到单例模式写法。 一、懒人写法(...

  • iOS单例模式的正确写法

    单例模式很常见,但是,能真正把单利模式写对的却很少。在iOS中,一般我们都是用官方推荐的写法来写单例: URLMa...

  • iOS 单例模式的写法

    单例模式确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例。意思只有一个实例。 错误写法(非线程安全...

网友评论

  • MMMille:第二种写法有一个疑惑: static AccountManager *defaultManager = nil;这一句是写在方法里的,, 当第二次调用sharedManager的时候, defaultManager不会被置为nil吗?
    凌巅:@明銮 静态变量,整个类里面只有一份,设置后就会一直有值
  • LGirl:亲爱的,你的线程单例写的有问题,是();不是{}
    凌巅:@LGirl 哦哦,是写错。。谢谢!

本文标题:iOS单例模式的写法

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