IOS 单例
来源:互联网 发布:雷电抢购软件 编辑:程序博客网 时间:2024/05/18 02:42
上次面试中面试用到了单例模式
这个模式不仅仅是java 中常用 并且OC中也经常用到
下面解析一下OC中单例的步骤
单例的创建为以下步骤
一: 创建静态实例 初始化 设置为nil
二:构造方法中检查 该单例对象是否为nil 如果为nil 则新建 返回实例类
三 :重写allocwithzone 方法 保证多次调用alloc 和init方法的时候不会产生新的对象
四:适当实现 allocwithzone copywithzone release 和autorelease
事例代码一
static RootViewController *shareRootViewController = nil;+(RootViewController *)sharedController{ @synchronized(self){ if(shareRootViewController == nil){ shareRootViewController = [[[self alloc] init] autorelease]; } } return shareRootViewController;}
+(id)allocWithZone:(NSZone *)zone{ @synchronized(self){ if (shareRootViewController == nil) { shareRootViewController = [super allocWithZone:zone]; return shareRootViewController; } } return nil;}
代码事例2
#import "SingleInstance.h"static SingleInstance *singleInstance=nil;@implementation SingleInstance+(SingleInstance *) getInstance{ @synchronized(self) { if(!singleInstance) { singleInstance=[[self alloc] init]; NSLog(@"第一次创建"); }else{ NSLog(@"没有创建"); } } return singleInstance;}@end
- iOS单例模式
- iOS 单例模式
- IOS 单例模式
- iOS单例
- iOS 单例模式
- IOS 单例
- IOS 单例
- IOS单例模式
- ios单例模式
- iOS单例
- iOS 单例,委托
- iOS 单例模式
- iOS 单例模式
- IOS单例模式
- ios单例Singleton
- iOS 单例
- iOS 单例浅谈
- IOS 之 单例
- iPhone开发关于UDID和UUID的一些理解
- Windows下usb接口驱动技术(二)
- An introduction to C++ Traits
- IOS 自定义导航栏背景
- FastReport.Net教程大全
- IOS 单例
- 黑马程序员 JAVA__高新技术--泛型总结
- AUTOSAR
- UVA 11538 Chess Queen
- 【图文并茂】人人都会修改APK,美化,汉化,去广告
- VC 设置系统时间
- mongodb简单查询
- 百度地图离线API及地图数据下载工具-尝鲜篇
- Xcode运行时错误:Could not launch "*.app"--No such file or directory(Users/*/Library/...)