iOS under Singleton mode implementation (Objective-c arc GCD)

Source: Internet
Author: User
Tags gcd

The singleton pattern ensures that a class has only one instance, and instantiates itself and provides this instance to the system as a whole.

Here the main introduction under ARC, the use of GCD to achieve a single case.

First step: Declare a static instance

Static Soundtool *_instance;

Step two: Overriding the initialization method

+ (ID) Allocwithzone: (struct _nszone *) zone

This method is called when the object is initialized to allocate memory, and when overridden, even if the user does not use the shared method to get the instance, its initialization can still guarantee that the same instance will be obtained.

After GCD, a convenient way to ensure that a code is executed only once is to provide a dispatch_once.

This code method does not need to be carefully memorized. The code snippet has been built into Xcode. When you knock down the dispath_once, you'll have smart hints.

Step three: Declare a class method to share an instance

+ (soundtool *) Sharedsoundtool

?
@implementation SoundToolstatic SoundTool *_instance;+ (SoundTool *)sharedSoundTool{     static dispatch_once_t onceToken;    dispatch_once(&onceToken, ^{        _instance=[self new];     });    return _instance; }+ (id)allocWithZone:(struct _NSZone *)zone {     static dispatch_once_t onceToken;    dispatch_once(&onceToken, ^{        _instance=[super allocWithZone:zone];    });     return_instance; } @end

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.