IOS 单例模式(非ARC)
singleton_h :连接字符串和参数
// ## : 连接字符串和参数 #define singleton_h(name) + (instancetype)shared##name; #define singleton_m(name) \ static id _instance; \ + (id)allocWithZone:(struct _NSZone *)zone \ { \ static dispatch_once_t onceToken; \ dispatch_once(&onceToken, ^{ \ _instance = [super allocWithZone:zone]; \ }); \ return _instance; \ } \ \ + (instancetype)shared##name \ { \ static dispatch_once_t onceToken; \ dispatch_once(&onceToken, ^{ \ _instance = [[self alloc] init]; \ }); \ return _instance; \ } \ \ - (oneway void)release \ { \ \ } \ \ - (id)autorelease \ { \ return _instance; \ } \ \ - (id)retain \ { \ return _instance; \ } \ \ - (NSUInteger)retainCount \ { \ return 1; \ } \ \ + (id)copyWithZone:(struct _NSZone *)zone \ { \ return _instance; \ }
调用单例模式 Singleton.h /.m
#import <Foundation/Foundation.h> #import "Singleton.h" @interface HMMainTool : NSObject singleton_h(MainTool) @end
#import "HMMainTool.h" @implementation HMMainTool singleton_m(MainTool) @end
调用类
#import "HMViewController.h" #import "HMAudioTool.h" #import "HMNetTool.h" #import "HMMainTool.h" @interface HMViewController () @end @implementation HMViewController - (void)viewDidLoad { [super viewDidLoad]; HMAudioTool *audio1 = [[HMAudioTool alloc] init]; HMAudioTool *audio2 = [HMAudioTool sharedAudioTool]; NSLog(@"1111%p %p", audio1, audio2); HMNetTool *net1 = [[HMNetTool alloc] init]; HMNetTool *net2 = [HMNetTool sharedNetTool]; NSLog(@"2222%p %p", net1, net2); HMMainTool *main1 = [[HMMainTool alloc] init]; HMMainTool *main2 = [HMMainTool sharedMainTool]; NSLog(@"333%p %p", main1, main2); } @end