码迷,mamicode.com
首页 > 移动开发 > 详细

IOS单例

时间:2015-04-28 14:20:05      阅读:139      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!