IOS Learning Note--0008 (singleton mode)

Source: Internet
Author: User

1. What is a singleton mode?

The popular saying is: A class, can only instantiate once

2. Under what circumstances is a singleton mode used?

① creates instances with wasted resources, and the more instances are not controlled.

② when different threads are called, they may cause a different behavior.

③ instances to be accessed between multiple modules

④ other ...

3. Simple implementation

Here is an example of a student class to illustrate

  @interface   Student:nsobject  + (instancetype) sharedstudent;   @end   #import   " student.h   " static  Student* __stu;   @implementation   Student  + (instancetype) sharedstudent{ if  (__    Stu == nil) {__stu  = [[Student Alloc]init];  return   __stu;}   @end  

The above example is one of the simplest implementations of a single example (just to illustrate what a singleton is)

Here is a lazy approach, but also a common method of practical work, using macros to define the declaration and definition of a single case

#defineSynthesize_singleton_for_header (className) \+ (ClassName *) shared# #className;#defineSynthesize_singleton_for_class (className) \+ (ClassName *) shared# #className {StaticClassName *shared# #className =Nil;Staticdispatch_once_t Oncetoken; Dispatch_once (&oncetoken, ^{shared# #className=[[Self alloc] init];}); returnshared# #className;}//using Dispatch_once, this method means that this method executes only once during the application life cycle, which is a single-instance code that combines GCD under arc.

When used, you only need to write the corresponding code in the header file with the implementation file.

Also take student example, here I put this macro definition in a single header file Singleton.h

#import <Foundation/Foundation.h>#import"Singleton.h"@ Interface  Student:nsobjectsynthesize_singleton_for_header (Student); @end #import " Student.h " @implementation Studentsynthesize_singleton_for_class (Student); @end

IOS Learning Note--0008 (singleton mode)

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.