A singleton class is a special class in which only one object of that class exists in a process type, and only one object appears in an iOS app. This design pattern is used in many parts of the system framework, such as Nsfilemanager, uiapplication and so on.
- In the ARC environment, the interface file is:
//// DVISingleton.h////Copyright (c) 2014 Changsha Camp David Education. All rights reserved. //#import <Foundation/Foundation.h>@interface Dvisingleton: nsobject+ (instancetype ) Sharedsingleton; @end
Implementation file:
//Dvisingleton.m//Copyright (c) 2014 Changsha Camp David Education. All rights reserved.//#import"DVISingleton.h"@implementationdvisingleton+ (instancetype) sharedsingleton{static Dvisingleton *sharedobject =NilThread safe, only allowed to execute sequentiallyStaticdispatch_once_t Oncetoken;Dispatch_once (&oncetoken, ^{Create an object using the Allocwithzone: Method of the parent class sharedobject = [[Super Allocwithzone:NULL] init]; });return sharedobject;} - (ID) init{if (self = [super Init]) {} return Self;} + (id) Allocwithzone: (struct _nszone *) zone{return [self Sharedsingleton];} -(id) copy{ return void) dealloc{} @end
- Implementation files in non-ARC environments:
#import"DVISingleton.h"@implementationdvisingleton+ (instancetype) sharedsingleton{static Dvisingleton *sharedobject =NilThread safe, only allowed to execute sequentiallyStaticdispatch_once_t Oncetoken;Dispatch_once (&oncetoken, ^{Create an object using the Allocwithzone: Method of the parent class sharedobject = [[Super Allocwithzone:NULL] init]; });return sharedobject;} + (ID) Allocwithzone: (Nszone *) Zone {return [[Self Sharedsingleton] retain];} - (ID) Copywithzone: (Nszone *) Zone {ReturnSelf;} - (ID) Retain {ReturnSelf;} - (unsigned) Retaincount {return Uint_max;Denotes an object, cannot be released}-(oneway void) Release { //never release}-(id) autorelease {return self;} -(id) init { if (self = [super Init]) {} return Self;} -(void) dealloc {[ super Dealloc];} @end
Objective-c Singleton mode