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.