Singleton mode for ios

Source: Internet
Author: User

The Singleton mode only has one instance. Instantiate the instance and provide the instance to the entire system.

Create Singleton Mode 1. First, in the. h file
#import <Foundation/Foundation.h>@interface SingletonClass : NSObject+ (id) sharedInstance;@end

2. In the. m file
#import "SingletonClass.h"@implementation SingletonClassstatic SingletonClass * getInstance;+ (id) sharedInstance {    @synchronized ([SingletonClass class]) {        if (getInstance == nil) {            getInstance = [[SingletonClass alloc] init];        }    }    return getInstance;}@end

Here is an example of SingletonClass. Singleton Mode
[[SingletonClass sharedInstance] xxx];

The destruction and destruction of a singleton is the release of the singleton. The delegate method is as follows when the application is terminated.
- (void)applicationWillTerminate:(UIApplication *)application{    [SingletonClass destroyDealloc];}


Destruction Method
+ (void)destroyDealloc{    if ([getInstance retainCount] != 1)        return;        [getInstance release];    getInstance = nil;}

Summary of the benefits of Singleton: 1. instance control: Singleton will prevent other objects from instantiating copies of their own Singleton objects, so that all objects can access a unique instance.
2. Flexibility: Because the class controls the instantiation process, the class can be more flexible to modify the instantiation process. Disadvantages: The Singleton mode makes the object global, reducing the flexibility of each module.

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.