Implementing a singleton in iOS

Source: Internet
Author: User
Tags gcd

In iOS, the memory allocation method for all objects calls Allocwithzone, such as the constructor alloc, so overriding this method allows you to implement a singleton.

Xcode is pre-written to implement the code quick instructions, knock Dispatch_once will see. This is a singleton code with GCD implementations.

The implementation code is as follows:

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 +(id)allocWithZone:(struct _NSZone *)zone {     static LYDemo * instance;     //是线程安全的,onceToKen默认是0     static dispatch_once_t onceToken;     //dispatch_once宏可以保证代码中的代码只会被执行一次。     dispatch_once(&onceToken, ^{         instance = [super allocWithZone:zone];     });     return instance; } //上面代码只是保证了这个类只能有一个实例,而易读性略差,我们应该模仿系统的单例方式。 +(instancetype)sharedDemo {     return [[self alloc]init]; }

To implement a single-case procedure:

1. Rewrite the Allocwithzone method and use GCD pre-written code block Dispatch_once snippet.

2. Create a method that starts with GKFX and mimics the system's singleton.

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.