Objective-C中严谨的单例模式
网上很多资料都只用一个dispatch_once其实是不严谨的
废话不多说,直接上代码(支持MRC/ARC混编)
头文件:SingletonClass.h
// // SingletonClass.h // Singleton // // Created by iospp on 15/12/25. // Copyright © 2015年 iospp. All rights reserved. // #import <Foundation/Foundation.h> @interface SingletonClass : NSObject + (instancetype)singletonInstance; @end
实现文件:SingletonClass.m
// // SingletonClass.m // Singleton // // Created by iospp on 15/12/25. // Copyright © 2015年 iospp. All rights reserved. // #import "SingletonClass.h" @implementation SingletonClass static SingletonClass *singletonInstance = nil; #pragma mark - ARC + (instancetype)singletonInstance{ static dispatch_once_t once; dispatch_once(&once, ^{ singletonInstance = [[self alloc] init]; }); return singletonInstance; } + (instancetype)allocWithZone:(struct _NSZone *)zone{ static dispatch_once_t once; dispatch_once(&once, ^{ singletonInstance = [super allocWithZone:zone]; }); return singletonInstance; } - (id)copyWithZone:(struct _NSZone *)zone{ return singletonInstance; } #pragma mark - MRC #if __has_feature(objc_arc) #else - (instancetype)retain{ return singletonInstance; } - (NSUInteger)retainCount{ return 1;//此处也可以返回max } - (oneway void)release{ } - (instancetype)autorelease{ return singletonInstance; } #endif @end
测试代码:main.m
// // main.m // Singleton // // Created by iospp on 15/12/25. // Copyright © 2015年 iospp. All rights reserved. // #import <Foundation/Foundation.h> #import "SingletonClass.h" int main(int argc, const char * argv[]) { @autoreleasepool { SingletonClass *s1 = [SingletonClass singletonInstance]; SingletonClass *s2 = [[SingletonClass alloc] init]; SingletonClass *s3 = [s1 copy]; NSLog(@"release前s1→%@",s1); NSLog(@"release前s2→%@",s2); NSLog(@"release前s3→%@",s3); #if __has_feature(objc_arc) #else [s1 release]; [s2 release]; [s3 release]; #endif NSLog(@"release后s1→%@",s1); NSLog(@"release后s2→%@",s2); NSLog(@"release后s3→%@",s3); } return 0; }