iOS基础之单例

目录


单例: 程序运行期间(从点击App开始运行到关掉App结束运行),该类只会创建一个实例(对象指针存在于静态区,对象在堆中所占的空间 只会在程序终止后才会被释放)。

使用

YTAccount.h

#import 
@interface YTAccount : NSObject
+(instancetype)sharedAccount;
@end

YTAccount.m

#import "YTAccount.h"

@implementation YTAccount
static YTAccount *_sharedAccount;

// 用于外部访问
+(instancetype)sharedAccount{
    return [self new];
}


// 调用alloc会调用本方法(若不实现,用allocWithZone多次创建对象得到的不是单例)
+(instancetype)allocWithZone:(struct _NSZone *)zone{
/*
// 方法一
    // 线程锁(防止多线程同时调用)
    @synchronized (self) {
        if(!_sharedAccount){
            _sharedAccount=[super allocWithZone:zone];
        }
    }
    return _sharedAccount;
*/
    
// 方法二
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        //
        if(!_sharedAccount){
        
            _sharedAccount=[super allocWithZone:zone];
        }
    });
    return _sharedAccount;
}

// 避免使用copy mutableCopy方法时再次创建
-(id)copyWithZone:(NSZone *)zone{
    return _sharedAccount;
}
-(id)mutableCopyWithZone:(NSZone *)zone{
    return _sharedAccount;
}
@end

优化使用(方案一)

放在pch中

#define shareH(name) +(instancetype)share##name;

#if __has_feature(objc_arc)

#define shareM(name) static id _instance;\
+(instancetype)allocWithZone:(struct _NSZone *)zone\
{\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instance = [super allocWithZone:zone];\
});\
return _instance;\
}\
\
+(instancetype)share##name\
{\
return [self new];\
}\
-(id)copyWithZone:(NSZone *)zone\
{\
return _instance;\
}\
\
-(id)mutableCopyWithZone:(NSZone *)zone\
{\
return _instance;\
}
#else
#define singleM(name) static id _instance;\
+(instancetype)allocWithZone:(struct _NSZone *)zone\
{\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instance = [super allocWithZone:zone];\
});\
return _instance;\
}\
\
+(instancetype)share##name\
{\
return [self new];\
}\
-(id)copyWithZone:(NSZone *)zone\
{\
return _instance;\
}\
-(id)mutableCopyWithZone:(NSZone *)zone\
{\
return _instance;\
}\
-(oneway void)release\
{\
}\
\
-(instancetype)retain\
{\
return _instance;\
}\
\
-(NSUInteger)retainCount\
{\
return MAXFLOAT;\
}
#endif

使用

  .h中  shareH(类名)
  .m中  shareM(类名)

优化使用(方案二)

实现一个单例基类
需要单例时继承即可

你可能感兴趣的:(iOS基础之单例)