Objective-C ARC单例模式代码

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

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

//
//  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;
}

至此,希望你喜欢

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容