Single-instance mode for iOS development

Source: Internet
Author: User

1 , overview

single-case mode is a common software design pattern , which can ensure that a class has only one instance in the system and that the instance is easy to access, thus it is convenient to control the number of instances and save system resources.

If you want to have only one object for a class in the system, Singleton mode is the best solution, and the most common single case in iOS is uiapplication.

Application Scenarios:

Audio playback, background music!

Hardware resources: Accelerators, [UIScreen Mainscreen]

It is generally through sharedxx, mainxxx to obtain this singleton object.

Common interview questions: handwritten singleton

Advantages:

You can prevent other objects from instantiating a copy of a singleton object, ensuring that all objects have access to a unique instance

Disadvantages:

Once a singleton object is established, the object pointer is stored in the static area, and the memory space allocated by the Singleton object in the heap will not be released until the application terminates.

2 , single-instance implementation steps

First step: Rewrite Allocwithzone Method

The Allocwithzone method is a method that is eventually called when an object allocates memory space, overriding the method, guaranteeing that only one memory space is allocated

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

{

Static Ticket *instance;

The static dispatch_once_t oncetoken;//is used to detect if it is only executed once

Dispatch_once is thread-safe and can be implemented in a multi-threaded environment where the code in the block is only executed once

Dispatch_once (&oncetoken, ^{

instance = [Super Allocwithzone:zone];

});

return instance;

}

Step Two: Establish sharedxxx class method for easy access to other classes

+ (Instancetype) sharedticket

{

return [[Self alloc] init];

}

Single-instance mode for iOS development

Related Article

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.