Categories
Swift

Swift in the single mode

In the process of writing the code,We will meet when the need to ensure that only one instance of the global,This time use the singleton pattern。

Single mode--this ensures that only one instance of a class,And provide a global point of access to。

What about how to implement the singleton pattern? We take a look at the classic Java code,How to implement the singleton pattern。

Our online search for "Java singleton pattern" will be able to find plenty of readily available code snippets,Here are random excerpts of a report:

Then,How to use the singleton pattern in the Swift?

In accordance with the "common sense",You may be written like this:

In theory, "Singleton inited!" Output only once,But it really is this you?

We have a try:

The output results are as follows:

It didn't seem to matter,Then we try again:

Here we simply get the background queue,Then concurrently executed 1000 times access the instance,So in theory should also output a "Singleton inited!" The remaining 999 times,Are repeated access to the same instance,So true is it?

Obviously not-but it's not be reinitialized each time – that is to say,In the case of concurrent,This way is not safe,There is some probability that could result in duplicate initialization of,Then put into practice environment,Resulting in highly concurrent cases your data is reset、Empty。

Swift in the singleton pattern

So what exactly is the how to thread the thread safe? We change the code before:

Here we remove the getSingleton() This Getter ,Directly in the static property to initialize its own,Here is using the lazy characteristic of Swift,It will be in time for the first class,Keep references after the。

So how should I use it? We just changed the test code:

Where the highlighted row is modified,Same with 1000,Program execution results:

Finally,Implementation of results and we expect the same。

Original article written by Gerber drop-off:R0uter's Blog » Swift in the single mode

Reproduced Please keep the source and description link:https://www.logcg.com/archives/1734.html

By R0uter's Blog

The non-declaration,I have written articles are original,Reproduced, please indicate the link on this page and my name。

Leave a Reply

Your email address will not be published. Required fields are marked *