美文网首页
Swift/OC 单例-Singleton

Swift/OC 单例-Singleton

作者: 66b6d3e5fc98 | 来源:发表于2017-05-05 23:04 被阅读49次

单例——单独的实例,只实例化一次,数据全局共享。

Swift

open class CD_Singleton {
    private init() {}//必须要 private
    open static let shared = CD_Singleton()
}

OC

---------- .h
#import <Foundation/Foundation.h>
@interface CD_Single : NSObject
#pragma mark ----- 单例及打印测试该单例 -----
@property(nonatomic,strong) NSString *name;
+ (CD_Single*)shared;
+ (void)cd_print;
@end
---------- .m
#import "CD_Single.h"
static CD_Single* shared = nil;
@implementation CD_Single
#pragma mark ----- 单例 -----
+ (CD_Single*) shared
{
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        if (shared == nil) {
            shared = [[self alloc] init];
        }
        
    });
    return shared;
}
/**
 覆盖该方法主要确保当用户通过[[Singleton alloc] init]创建对象时对象的唯一性,alloc方法会调用该方法,只不过zone参数默认为nil,因该类覆盖了allocWithZone方法,所以只能通过其父类分配内存,即[super allocWithZone:zone]
 */
+(id)allocWithZone:(struct _NSZone *)zone
{
    static dispatch_once_t token;
    dispatch_once(&token, ^{
        if(shared == nil){
            shared = [super allocWithZone:zone];
        }
    });
    return shared;
}
//自定义初始化方法
- (instancetype)init
{
    self = [super init];
    if(self){
        
    }
    return self;
}
//覆盖该方法主要确保当用户通过copy方法产生对象时对象的唯一性
- (id)copy
{
    return self;
}
//覆盖该方法主要确保当用户通过mutableCopy方法产生对象时对象的唯一性
- (id)mutableCopy
{
    return self;
}
//自定义描述信息,用于log详细打印
- (NSString *)description
{
    return [NSString stringWithFormat:@"memeory address:%p,property name:%@",self,self.name];
}
//测试
+ (void)cd_print {
    CD_Single *defaultManagerSingleton =[CD_Single shared];
    NSLog(@"defaultManagerSingleton:\n%@",defaultManagerSingleton);
    CD_Single *allocSingleton = [[CD_Single alloc] init];
    NSLog(@"allocSingleton:\n%@",allocSingleton);
    CD_Single *copySingleton = [allocSingleton copy];
    NSLog(@"copySingleton:\n%@",copySingleton);
    CD_Single *mutebleCopySingleton = [allocSingleton mutableCopy];
    NSLog(@"mutebleCopySingleton:\n%@",mutebleCopySingleton);
}
@end

相关文章

网友评论

      本文标题:Swift/OC 单例-Singleton

      本文链接:https://www.haomeiwen.com/subject/tpostxtx.html