为了账号安全,请及时绑定邮箱和手机立即绑定

Objective-C ARC单例模式代码

标签:
iOS

单例模式的作用我就不在此解释了,使用单例模式的代码展示如下。

首先,在头文件中,要禁用生成实例的方法,并且声明单例的类方法

//
//  MySingleton.h
//  SingleTon
//
//  Created by Realank on 15/8/4.
//  Copyright (c) 2015年 Realank. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface MySingleton : NSObject

@property (copy,nonatomic) NSString* string;

+(instancetype) sharedInstance;

// clue for improper use (produces compile time error)
+(instancetype) alloc __attribute__((unavailable("alloc not available, call sharedInstance instead")));
-(instancetype) init __attribute__((unavailable("init not available, call sharedInstance instead")));
+(instancetype) new __attribute__((unavailable("new not available, call sharedInstance instead")));

@end

在单例类方法中创建单例实例,这例使用了dispatch_once这个tricky

//
//  MySingleton.m
//  SingleTon
//
//  Created by Realank on 15/8/4.
//  Copyright (c) 2015年 Realank. All rights reserved.
//

#import "MySingleton.h"

@implementation MySingleton

+(instancetype) sharedInstance {
    static dispatch_once_t pred;
    static id shared = nil; //设置成id类型的目的,是为了继承
    dispatch_once(&pred, ^{
        shared = [[super alloc] initUniqueInstance];
    });
    return shared;
}

-(instancetype) initUniqueInstance {

    if (self = [super init]) {
        _string = @"hello";
    }

    return self;
}

@end

这个单例类使用方法如下:

//
//  main.m
//  SingleTon
//
//  Created by Realank on 15/8/4.
//  Copyright (c) 2015年 Realank. All rights reserved.
//

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

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here...
        MySingleton *sgt = [MySingleton sharedInstance];
        NSLog(@"%@",sgt.string);
    }
    return 0;
}

至此,希望你喜欢

点击查看更多内容
1人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
移动开发工程师
手记
粉丝
11
获赞与收藏
446

关注作者,订阅最新文章

阅读免费教程

感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消