Singleton
單例的正確寫(xiě)法(ARC環(huán)境下)
TestSingleton.h
#import <Foundation/Foundation.h>
@interface TestSingleton : NSObject <NSCopying>
@property (nonatomic , copy) NSString *gid;
@property (nonatomic , strong) NSMutableArray *groups;
+ (instancetype)shareInstance;
@end
TestSingleton.m
#import "TestSingleton.h"
@implementation TestSingleton
static TestSingleton *instance = nil;
+ (instancetype)shareInstance
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [[super allocWithZone:NULL] init];
instance.groups = [[NSMutableArray alloc] init];
instance.gid = @"0";
});
return instance;
}
//攔截外部調(diào)用alloc方法創(chuàng)建單例實(shí)例
+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
return [TestSingleton shareInstance];
}
//攔截外部調(diào)用copy方法拷貝單例實(shí)例
- (id)copyWithZone:(NSZone *)zone
{
return [TestSingleton shareInstance];
}
//測(cè)試單例對(duì)象和相關(guān)屬性的打印地址
- (NSString *)description
{
NSString *result = @"";
result = [result stringByAppendingFormat:@"<%@ : %p>", [self class], self];
result = [result stringByAppendingFormat:@" gid = %p", self.gid];
result = [result stringByAppendingFormat:@" groups = %p", self.groups];
return result;
}
@end
關(guān)于TestSingleton.m中的這兩個(gè)方法
+ (instancetype)allocWithZone:(struct _NSZone *)zone
- (id)copyWithZone:(NSZone *)zone
我們知道花履,創(chuàng)建對(duì)象的步驟分為申請(qǐng)內(nèi)存(alloc)橘券、初始化(init)這兩個(gè)步驟净刮,我們要確保對(duì)象的唯一性誊垢,因此在第一步這個(gè)階段我們就要攔截它悔捶。當(dāng)我們調(diào)用alloc方法時(shí)响迂,OC內(nèi)部會(huì)調(diào)用allocWithZone這個(gè)方法來(lái)申請(qǐng)內(nèi)存,我們覆寫(xiě)這個(gè)方法渗勘,然后在這個(gè)方法中調(diào)用shareInstance方法返回單例對(duì)象沐绒,這樣就可以達(dá)到我們的目的⊥梗拷貝對(duì)象也是同樣的原理乔遮,覆寫(xiě)copyWithZone方法(要先遵循NSCopying協(xié)議,NSObject并未遵循該協(xié)議)取刃,然后在這個(gè)方法中調(diào)用shareInstance方法返回單例對(duì)象蹋肮。