單例類是一種特殊的類,在一個進程種只會存在一個該類的對象,在iOS應用中只會出現一個對象。這種設計模式在系統框架中許多地方都使用了,如NSFileManager、UIApplication等。
//
// DVISingleton.h
//
// Copyright (c) 2014 長沙戴維營教育. All rights reserved.
//
#import
@interface DVISingleton : NSObject
+ (instancetype)sharedSingleton;
@end
實現文件:
//
// DVISingleton.m
//
// Copyright (c) 2014 長沙戴維營教育. All rights reserved.
//
#import "DVISingleton.h"
@implementation DVISingleton
+ (instancetype)sharedSingleton
{
static DVISingleton *sharedObject = nil;
//線程安全,只允許執行依次
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
//使用父類的allocWithZone:方法創建對象
sharedObject = [[super allocWithZone:NULL] init];
});
return sharedObject;
}
- (id)init
{
if (self = [super init]) {
}
return self;
}
+ (id)allocWithZone:(struct _NSZone *)zone
{
return [self sharedSingleton];
}www.Bkjia.com
- (id)copy
{
return self;
}
- (void)dealloc
{
}
@end
#import "DVISingleton.h"
@implementation DVISingleton
+ (instancetype)sharedSingleton
{
static DVISingleton *sharedObject = nil;
//線程安全,只允許執行依次
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
//使用父類的allocWithZone:方法創建對象
sharedObject = [[super allocWithZone:NULL] init];
});
return sharedObject;
}
+ (id)allocWithZone:(NSZone *)zone {
return [[self sharedSingleton] retain];
}
- (id)copyWithZone:(NSZone *)zone {
return self;
}
- (id)retain {
return self;
}
- (unsigned)retainCount {
return UINT_MAX; //denotes an object that cannot be released
}
- (oneway void)release {
// never release
}
- (id)autorelease {
return self;
}
- (id)init {
if (self = [super init]) {
}
return self;
}
- (void)dealloc {
[super dealloc];
}
@end