The Singleton model is widely used on the Internet. Today, I am posting my personal understanding of Singleton mode. Only one instance exists in the entire app, and the instance is executed only once. After the instance is completed, it cannot be released by people (when the App is closed, the system recycles it by itself ).
That is to say, if we write a class that meets the preceding conditions, we can also call this class A singleton.
In non-ARC projects, we need to control the retaincount parameters added for alloc, retain, copy, and so on, and add control for release and autorelease operations that reduce retailcount, to ensure that a single instance is never released.
In the ARC factory, memory management is done systematically. Specifically, a Singleton does not exist, so the system will recycle it when the memory is tight, duplicate instances may exist. In this way, the data stored in your instance will be lost, so it does not exist. (Personal understanding)
Next I will share with you how I create a singleton.
Non-ARC singleton:
#import <Foundation/Foundation.h>@interface BaseSingle : NSObject+(id)getInstance;@end
In the. m file, add control to the rewrite Method
#import "BaseSingle.h"@implementation BaseSingle+(id)getInstance{ return nil;}+(id)allocWithZone:(struct _NSZone *)zone{ return [[self getInstance] retain];}-(id)copyWithZone:(struct _NSZone *)zone{ return self;}-(id)retain{ return self;}-(NSUInteger)retainCount{ return NSUIntegerMax;}-(oneway void)release{ return;}-(id)autorelease{ return self;}
Then we inherit the BaseSingle to override the getInstance method when calling.
For example, FileDownLoadManager inherits BaseSingle.
+(FileDownLoadManager *)getInstance{ static FileDownLoadManager * shareFileDownLoadManager = nil; @synchronized(self){ if (shareFileDownLoadManager == nil) { shareFileDownLoadManager = [NSAllocateObject([self class], 0, NULL) init]; } } return shareFileDownLoadManager;}
Such a proper Singleton is complete.
ARC singleton:
The ARC Singleton will not be described here. I believe everyone understands it... Hey