iOS学习笔记6-单例理解

单例小结:如下是官方文档

Declaration

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

小结:

  1. 使用dispatch_once方法可以创建单例或者某些初始化动作时使用,以保证其唯一性,

  2. 该方法是线程安全的,所以请放心大胆的在子线程中使用(前提是你的dispatch_once_t *predicate 对象一定是在全局或者静态对象,如果不是,那结果不可预知




OC中单例的写法

+ (instancetype)sharedTools {
    static id instance;
    
    static dispatch_once_t onceToken;
    
    NSLog(@"---> %ld",onceToken);
    
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    
    return instance;
}

Swift中单例的写法

单例的写法和懒加载很像,静态区的对象只能设置一次数值,第一次使用时才创建对象

    static let sharedTools2: SoundTools = {
        print("wwwwwwww")
        
        return SoundTools()
    }()


转载于:https://my.oschina.net/u/2617794/blog/609149

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值