Introduction to singleton
Singleton mode is the most commonly used design mode in iOS development. Singleton mode allows various modules of the program to share data without manual transmission. So the singleton class is a very important mode that we should understand. This mode runs through the iPhoneSDK. For example, a method of UIApplication is called using application to share the UIApplication instance of the current program.
Implementation of Singleton
Add an external data class and declare it in external data. h as follows:
#import
@interface ShareData : NSObject{ NSString *string;}@property (nonatomic, retain) NSString *string;+ (id)sharedData;@end
Implement this class in external data. m:
#import "ShareData.h"@implementation ShareData@synthesize someProperty;#pragma mark Singleton Methods+ (id)sharedData{ static ShareData *sharedData = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sharedData = [[self alloc] init]; }); return sharedData;}- (id)init{ if (self = [super init]) { self.string = [[[NSString alloc] initWithString:@"123"] autorelease]; } return self;}- (void)dealloc{ self.string = nil; [super dealloc];}
Defines a globally unique static variable named external data in the translation unit. You can call the static method external data to initialize and obtain the variable. The dispatch_once method of Grand Central Dispatch (GCD) is called to ensure that static variables are initialized only once, and dispatch_once is the thread security guaranteed by the system.
The compile data method is written as follows without using GCD:
+ (id)sharedData{ static ShareData *sharedData = nil; @synchronized(self) { if (sharedData == nil) { sharedMyManager = [[self alloc] init]; } } return sharedData;}
The Singleton mode is as follows:
ShareData *shareData = [ShareData sharedData];
The implementation code in non-ARC (Automatic Reference Counting) is as follows:
#import "ShareData.h"static ShareData *shareData = nil;@implementation ShareData@synthesize string;#pragma mark Singleton Methods+ (id)shareData{ @synchronized(self) { if(shareData == nil) { shareData = [[super allocWithZone:NULL] init]; } } return shareData;}+ (id)allocWithZone:(NSZone *)zone{ return [[self shareData] retain];}- (id)copyWithZone:(NSZone *)zone{ return self;}- (id)retain{ return self;}- (unsigned)retainCount{ return UINT_MAX; //denotes an object that cannot be released}- (oneway void)release{ // never release}- (id)autorelease{ return self;}- (id)init{ if (self = [super init]) { string = [[NSString alloc] initWithString:@"123"]; } return self;}- (void)dealloc{ [string release]; [super dealloc];}@end