首页 > 其他 > 详细

单例实现方式

时间:2015-10-26 19:09:34      阅读:235      评论:0      收藏:0      [点我收藏+]
#import "ApplicationSupport.h"
static ApplicationSupport *support = nil;
@implementation ApplicationSupport
+ (ApplicationSupport *)sharedSupport
{
    //加锁使之线程安全
    @synchronized(self){
        if(support == nil){
            support = [[ApplicationSupport alloc]init];
        }
    }
    return support;
}
//重写NSObject中的此方法,相当于重写了alloc
+ (id)allocWithZone:(struct _NSZone *)zone
{
    if(support == nil){
        support = [super allocWithZone:zone];
        return support;
    }
    return nil;
}

- (id)copyWithZone:(NSZone *)zone
{
    return self;
}



//此类是一个单例类,这个类的对象只能有一个
#import <Foundation/Foundation.h>

@interface ApplicationSupport : NSObject <NSCopying>
//提供一个类方法,返回那个唯一的对象
+ (ApplicationSupport *)sharedSupport;


int main(int argc, const char * argv[]) {
    ApplicationSupport *a1 = [[ApplicationSupport alloc]init];
    //ApplicationSupport *a2 = [[ApplicationSupport alloc]init];
    //ApplicationSupport *a1 = [ApplicationSupport sharedSupport];
    ApplicationSupport *a2 = [ApplicationSupport sharedSupport];
    ApplicationSupport *a3 = [a1 copy];
    NSLog(@"%p, %p, %p", a1, a2, a3);
    return 0;
}


单例实现方式

原文:http://my.oschina.net/u/2447084/blog/522232

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!