美文网首页Realank的iOS专题
Objective-C ARC单例模式代码

Objective-C ARC单例模式代码

作者: Realank | 来源:发表于2015-12-30 10:31 被阅读97次

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

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

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

至此,希望你喜欢

相关文章

  • iOS - 单例模式

    1.单例模式 1.1 概念相关 (1)单例模式 (2)使用场合 1.2 ARC实现单例 (1)步骤 (2)相关代码...

  • iOS开发-单例模式

    1.单例模式 1.1 概念相关 (1)单例模式 (2)使用场合 1.2 ARC实现单例 (1)步骤 (2)相关代码...

  • iOS之单例模式

    单例模式 1.1 概念相关 (1)单例模式 (2)使用场合 1.2 ARC实现单例 (1)步骤 (2)相关代码 1...

  • 单例模式

    1.单例模式 1.1 概念相关 (1)单例模式 (2)使用场合 1.2 ARC实现单例 (1)步骤 (2)相关代码...

  • 多线程(二)

    1.单例模式 1.1 概念相关 (1)单例模式 (2)使用场合 1.2 ARC实现单例 (1)步骤 (2)相关代码...

  • iOS单例一行实现(抽取单例宏)

    本文首先实现单例模式,然后对单例代码进行抽取宏,使其他类可以一句代码实现单例(只介绍ARC环境)本文代码 - 单例...

  • Objective-C ARC单例模式代码

    单例模式的作用我就不在此解释了,使用单例模式的代码展示如下。 首先,在头文件中,要禁用生成实例的方法,并且声明单例...

  • iOS 单例模式

    概念相关 (1)单例模式 (2)使用场合 2 ARC实现单例 (1)步骤 (2)相关代码 3 MRC实现单例 (1...

  • The Singleton Pattern 单例模式 教程

    1.ARC 单例模式 1.1ARC 单例模式 Person.h Person.m ViewController.m...

  • The Singleton Pattern 单例模式

    单例模式的作用 单例模式的使用场合 单例模式在ARC\MRC环境下的写法有所不同,需要编写2套不同的代码 可以用宏...

网友评论

    本文标题:Objective-C ARC单例模式代码

    本文链接:https://www.haomeiwen.com/subject/zleihttx.html