Objective-C ARC单例模式
2015-08-04 14:01
441 查看
// // 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
// // 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; }
相关文章推荐
- 设计模式之创建型模式 - 特别的变量问题
- C#单例模式(Singleton Pattern)实例教程
- php设计模式之单例、多例设计模式的应用分析
- javascript 单例/单体模式(Singleton)
- Objective-C的内省(Introspection)用法小结
- C++单例模式应用实例
- 浅谈Java编程中的单例设计模式
- Objective-C中常用的结构体NSRange,NSPoint,NSSize(CGSize),NSRect实例分析
- Objective-C中NSLog输出格式大全
- Python单例模式实例分析
- Swift调用Objective-C编写的API实例
- Swift、Objective-C、Cocoa混合编程设置指南
- Objective-c代码如何移植为Swift代码 Objective-c代码转移到Swift过程介绍
- Swift调用Objective-C代码
- Java单例模式实例简述
- objective-c中生成随机数的方法
- 在Swift中使用Objective-C编写类、继承Objective-C类
- Swift能代替Objective-C吗?
- Objective-C 消息传递机制详解
- 在一个项目中同时使用Swift和Objective-C代码混合编程的方法