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