iOS often uses design patterns-Singleton mode

Source: Internet
Author: User

Part I: Creating a Singleton object

A single case scenario:

Singleton mode is used when a class can have only one instance. Typically, this " singleton " represents a physical device, such as a printer, Or some kind of virtual resource or system attribute that cannot have multiple instances at the same time as an engine or data for a program.

It is necessary to use a singleton mode to control it.

What is a singleton mode?

A single case is a frequently used Software Design Patterns . When you apply this pattern, the class of the Singleton object must guarantee that only one instance exists. Most of the time, the entire system needs to have only one global object . This helps us coordinate the overall behavior of the system.

The singleton design pattern needs to achieve the following objectives: 1.) encapsulates a shared resource; 2.) provides a fixed instance creation method. 3.) Provide a standard instance access interface

Frequently used methods for defining a singleton (ARC+GCD)

Implement a class method to create a singleton object static ClassType *objname = nil; + (ClassType *) sharedinstance{static dispatch_once_t Onetoken = 0;dispatch_once (&oncetoken, ^{objName = [[Super Allo Cwithzone:null] [init];}); return objname; }//rewrite several methods. Prevents errors when creating a singleton object-(ID) init{if (self = [super init]) {//initializes various properties of the Singleton object}return self;} + (ID) allocwithzone: (struct _nszone *) Zone{return [self sharedinstance];} This is the method that is required to implement the Singleton object following the <NSCopying> protocol-(ID) Copywithzone: (struct _nszone *) Zone{return self;}
Part II: Use of uiapplication single case

Create an instance variable directly in the Appdelegate. These variables are then used in other files in the project.

Appdelegate *appdelegate = (appdelegate *) [[uiapplication shareapplication] delegate];appdelegate.a = 10086; appdelegate.globalstring = @ "China wants Unicom";

In this way, you can define a global instance variable.

For details, please refer to:http://blog.csdn.net/casablaneca/article/details/21074413

Part III: Using a singleton design pattern in a project

Description of the project: we want to trigger a change in one of the property values in the Singleton object with a button click event. Then using KVO to listen for this property on the two sub-views of Viewcontroller (Leftview, Rightview) is worth changing, and the changed values are displayed on Leftview and Rightview.

1.) Set a button and a trigger event on the Viewcontroller

-(Ibaction) RefreshData: (ID) SENDER{//STOCKFORKVO is a singleton object stockforkvo.price = Arc4random ()%100;}

2.) Use KVO in Lefeview and Rightview objects to listen for changes in the property values in the Singleton object

STOCKFORKVO = [StockData sharedinstance];    [Stockforkvo addobserver:self forkeypath:@ "Price" options:nskeyvalueobservingoptionnew| Nskeyvalueobservingoptionold context:null];//Implementation callback Method-(void) Observevalueforkeypath: (NSString *) KeyPath OfObject: (ID Object change: (nsdictionary *) Change context: (void *) context{    if ([KeyPath isequaltostring:@ "Price"]) {        Showlabel.text = [NSString stringwithformat:@ "%f", Stockforkvo.price];        NSLog (@ "Left change:%@", change);}    }

3.) After the implementation of the effect 2 see

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvy2fzywjsyw5ly2e=/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/southeast "style=" WIDTH:274PX; height:320px ">

Figure 2: The right side is the scene after the button event is triggered, and the left is the scene at the time of initialization

Source code for Project: http://download.csdn.net/detail/luozhonglan/8005001



iOS often uses design patterns-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.