首页 > 移动平台 > 详细

IOS单例

时间:2015-04-28 14:18:59      阅读:243      评论:0      收藏:0      [点我收藏+]
#import <Foundation/Foundation.h>
@interface FuCardSettings : NSObject
+ (FuCardSettings *)sharedInstance ;
@end
#import "FuCardSettings.h"

@implementation FuCardSettings

//================= 单例 ============== start
static FuCardSettings *sharedSettings = nil;
+ (FuCardSettings *)sharedInstance {
        if(sharedSettings  ==  nil){
            sharedSettings = [[[self alloc] init]autorelease];  
        }
    return  sharedSettings;
}

+ (id)allocWithZone:(NSZone *)zone {
    @synchronized(self) {
        if (sharedSettings == nil) {
            sharedSettings = [super allocWithZone:zone];
        }
    }
    return sharedSettings;
}

+ (id)copyWithZone:(NSZone *)zone {
    return self;
}

- (id)retain {
    return self;
}

- (NSUInteger)retainCount {
    return NSUIntegerMax;
}

- (oneway void)release {
}

- (id)autorelease {
    return self;
}
//================= 单例 ============== end

@end

上面是传统的单例:

还有一种用GCD实现的单例:

#import <Foundation/Foundation.h>

@interface Tool1 : NSObject

@property(nonatomic,copy)NSString *test;
+ (instancetype)instance;
@end


@implementation Tool1

+ (instancetype)instance
{
    static Tool1* tool;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        tool = [[Tool1 alloc] init];
        
    });
    return tool;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        _test = @"test";
    }
    return self;
}

@end

该写法具有以下几个特性:

1. 线程安全。

2. 满足静态分析器的要求。

3. 兼容了ARC







IOS单例

原文:http://my.oschina.net/u/936286/blog/407151

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!