iOS 创建单例的方法 dispatch_once

单例的运用场景是:一种类,该类只能实例化一个对象。

iOS 创建单例的方法有:dispatch_once

举例如下

假如有个全局的状态类,该类的接口部分如下:

@interface GlobalState ()
@end


该类的实现:

@implementation GlobalState

+ (GlobalState *)state
{
  static GlobalState *state = nil;
  
  static dispatch_once_t once;
  dispatch_once(&once, ^{
    state = [[M2GlobalState alloc] init];
  });
  
  return state;
}

@end

任何时候访问共享实例,需要做的仅是:
GlobalState* state = [GlobalState state];

该种方法的特点:

1 线程安全
        2 很好满足静态分析器要求
        3 和自动引用计数(ARC)兼容 
        4 仅需要少量代码

该方法的作用就是执行且在整个程序的声明周期中,仅执行一次 dispatch_once 当中的 block 对象。

有些需要在程序开头初始化的动作,也可以放到 dispatch_once 当中来执行,保证其仅执行一次。

这个函数需要一个断言来确定这个代码块是否执行,这个断言的指针要保存起来。

对于在应用中创建一个初始化一个全局的数据对象(单例模式),这个函数很有用。如果同时在多线程中调用它,这个函数将等待同步等待,直至该block调用结束。

这个断言的指针必须要全局化的保存,或者放在静态区内。使用存放在自动分配区域或者动态区域的断言,dispatch_once执行的结果是不可预知的。

使用该方法要注意的地方

(1)获取单例的方法为类方法

(2)用静态指针指向单例

(3)参数 dispatch_once_t 也为静态的,否则结果不可知。


以下是官方文档

dispatch_once

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

Declaration

SWIFT

func dispatch_once(_predicate:UnsafeMutablePointer<dispatch_once_t>,
                 
_ block:dispatch_block_t!)

OBJECTIVE-C

void dispatch_once(dispatch_once_t*predicate,dispatch_block_tblock);

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 (including Objective-C instance variables) is undefined.

Import Statement

import Dispatch

Availability

Available in iOS 4.0 and later.


dispatch_once_t

A predicate for use with the dispatch_once function.

Declaration

SWIFT

typealias dispatch_once_t = Int

OBJECTIVE-C

typedef longdispatch_once_t;

Discussion

Variables of this type must have global or static scope. The result of using this type with automatic or dynamic allocation is undefined. Seedispatch_once for details.

Import Statement

import Dispatch

Availability

Available in iOS 4.0 and later.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值