单例模式(arc)

单例模式(arc)

.h文件

@interface Singleton : NSObject

+ (Singleton *)sharedInstance;

@end

.m文件

__strong static Singleton *singleton = nil;

@implementation Singleton

// 这里使用的是ARC下的单例模式
+ (Singleton *)sharedInstance
{
	// dispatch_once不仅意味着代码仅会被运行一次,而且还是线程安全的
	static dispatch_once_t pred = 0;
	dispatch_once(&pred, ^{
	    singleton = [[super allocWithZone:NULL] init];
    
	});
	return singleton;
}
// 这里
+(id)allocWithZone:(NSZone *)zone
{
	return [self sharedInstance];
}

-(id)copyWithZone:(NSZone *)zone
{
    return self;
}

@end
原文地址:https://www.cnblogs.com/sunyanyan/p/5226844.html