单例模式(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
posted @ 2016-02-29 11:16  孙焱焱  阅读(191)  评论(0编辑  收藏  举报