• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Objective-C中严谨的单例模式

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

网上很多资料都只用一个dispatch_once其实是不严谨的

废话不多说,直接上代码(支持MRC/ARC混编)

 

头文件:SingletonClass.h

//
//  SingletonClass.h
//  Singleton
//
//  Created by iospp on 15/12/25.
//  Copyright © 2015年 iospp. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface SingletonClass : NSObject

+ (instancetype)singletonInstance;

@end

实现文件:SingletonClass.m

//
//  SingletonClass.m
//  Singleton
//
//  Created by iospp on 15/12/25.
//  Copyright © 2015年 iospp. All rights reserved.
//

#import "SingletonClass.h"

@implementation SingletonClass

static SingletonClass *singletonInstance = nil;

#pragma mark - ARC

+ (instancetype)singletonInstance{

    static dispatch_once_t once;
    
    dispatch_once(&once, ^{
        singletonInstance = [[self alloc] init];
    });
    
    return singletonInstance;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone{

    static dispatch_once_t once;
    
    dispatch_once(&once, ^{
        singletonInstance = [super allocWithZone:zone];
    });
    
    return singletonInstance;
}

- (id)copyWithZone:(struct _NSZone *)zone{
    
    return singletonInstance;
}

#pragma mark - MRC

#if __has_feature(objc_arc)

#else

- (instancetype)retain{
    
    return singletonInstance;
}

- (NSUInteger)retainCount{
    
    return 1;//此处也可以返回max
}

- (oneway void)release{
    
}

- (instancetype)autorelease{
    
    return singletonInstance;
}

#endif

@end

 测试代码:main.m

//
//  main.m
//  Singleton
//
//  Created by iospp on 15/12/25.
//  Copyright © 2015年 iospp. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "SingletonClass.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        
        SingletonClass *s1 = [SingletonClass singletonInstance];
        SingletonClass *s2 = [[SingletonClass alloc] init];
        SingletonClass *s3 = [s1 copy];
        
        NSLog(@"release前s1→%@",s1);
        NSLog(@"release前s2→%@",s2);
        NSLog(@"release前s3→%@",s3);
        
#if __has_feature(objc_arc)
        
#else
        
        [s1 release];
        [s2 release];
        [s3 release];
        
#endif
        
        NSLog(@"release后s1→%@",s1);
        NSLog(@"release后s2→%@",s2);
        NSLog(@"release后s3→%@",s3);
        
    }
    return 0;
}

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Objective-C:运行时runtime发布时间:2022-07-12
下一篇:
Objective-C(十八、谓语使用及实例说明)——iOS开发基础发布时间:2022-07-12
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap