# 03.为什么用dispatch-once实现单例

> 面试问到了 自己说到了这点(猜的是线程安全的查了一下确实是这样)

```
+ (XXXX *)sharedInstance
{
    static id sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}
```

`dispatch_once`是线程安全的,可以确保

## 参考

> <http://www.cnblogs.com/hellocby/archive/2012/08/24/2654488.html> <https://blog.csdn.net/qqMCY/article/details/88648000> 单例alloc 、 copy的处理


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://ryukiedev.gitbook.io/wiki/ios/duo-xian-cheng/wei-shi-mo-yong-dispatchonce-shi-xian-dan-li.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
