一,在MRC下,用传统的方式实现单例:
分布式
#import <Foundation/Foundation.h> @interface FuCardSettings : NSObject + (FuCardSettings *)sharedInstance ; @end
#import "FuCardSettings.h" @implementation FuCardSettings //================= 单例 ============== start static FuCardSettings *sharedSettings = nil; + (FuCardSettings *)sharedInstance { if(sharedSettings == nil){ sharedSettings = [[[self alloc] init]autorelease]; } return sharedSettings; } + (id)allocWithZone:(NSZone *)zone { @synchronized(self) { if (sharedSettings == nil) { sharedSettings = [super allocWithZone:zone]; } } return sharedSettings; } + (id)copyWithZone:(NSZone *)zone { return self; } - (id)retain { return self; } - (NSUInteger)retainCount { return NSUIntegerMax; } - (oneway void)release { } - (id)autorelease { return self; } //================= 单例 ============== end @end
二,在MRC下,用GCD实现单例:atom
#import <Foundation/Foundation.h> @interface FuCardSettings : NSObject + (FuCardSettings *)sharedInstance ; @end
@implementation FuCardSettings //定义一份变量(整个程序运行过程当中,只有一份) static id _instace; //构造方法 -(id)init { static id obj; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ obj = [super init]; if (obj) { } }); self=obj; return self; } //重写该方法,控制内存的分配,永远只分配一次存储空间 +(id)allocWithZone:(struct _NSZone *)zone { //里面的代码只会执行一次 static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _instace=[super allocWithZone:zone]; }); return _instace; } //类方法 +(id)sharedInstance { //里面的代码永远都只执行一次 static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _instace=[[self alloc]init]; }); return _instace; } //重写release方法 //oneway :分布式对象 -(oneway void)release { } //无论调用哪一个方法,返回的都是惟一的实例,因此这里self和instace是同样的 -(id)autorelease { return self; } -(id)retain { return self; } -(NSUInteger)retainCount { return 1; } +(id)copyWithZone:(struct _NSZone *)zone { return self; } @end
还有一种在ARC下用GCD实现的单例:spa
#import <Foundation/Foundation.h> @interface Tool1 : NSObject @property(nonatomic,copy)NSString *test; + (instancetype)instance; @end @implementation Tool1 + (instancetype)instance { static Tool1* tool; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ tool = [[Tool1 alloc] init]; }); return tool; } - (instancetype)init { static id obj=nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ obj = [super init]; if (obj) { } }); self=obj; return self; } @end
因为MRC是进行手动内存管理,因此须要实现下面的方法:code
- (id)retain { return self; }对象
- (NSUInteger)retainCount { return 1; }内存
- (oneway void)release {}it
- (id)autorelease { return self; }内存管理