OC单例写法

//
//  SingeTest.h
//  OC基础学习
//
//  Created by 麦子 on 15/5/29.
//  Copyright (c) 2015年 麦子. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface SingeTest : NSObject<NSCopying>

@property(nonatomic,copy) NSString *name;


+(id)shareSingeTest;  // 一个是:share 开头,一个是default开头命名。


@end
//
//  SingeTest.m
//  OC基础学习
//
//  Created by 麦子 on 15/5/29.
//  Copyright (c) 2015年 麦子. All rights reserved.
//

#import "SingeTest.h"
/***
 
    单例的步骤:  覆盖allocWithZone方法, 确保alloc的时候,不会产生新的对象。
 
                实现NScopying协议,覆盖 release,autorelease,retain, retaincount.方法
 
                加锁处理多线程中的问题。
 
 
 */
static SingeTest *singeTest = nil;

@implementation SingeTest


+(id)shareSingeTest{
    @synchronized(self){
        if (singeTest == nil) {
            singeTest = [[[self class] alloc] init];
        }
    }
    return singeTest;
};


+(id)allocWithZone:(struct _NSZone *)zone { // 初始化
    if (singeTest == nil) {
        singeTest = [super allocWithZone:zone];
    }
    return singeTest;
}


- (id)copyWithZone:(NSZone *)zone{  // copy
    
    return singeTest;
}


-(id)retain{

    return singeTest;
}

-(id)autorelease{
    
    return singeTest;
}


- (oneway void)release{

}

-(NSUInteger) retainCount{ // 最大值

    return UINT_MAX;
}


@end

 /**单例**/
       SingeTest *test1 = [SingeTest shareSingeTest];
       SingeTest *test2 = [[SingeTest alloc] init];
       SingeTest *test3 = [test1 copy];
        
        NSLog(@"---%@----%@-----+++-%@",test1,test2,test3);


运行结果如下:

2015-06-02 09:29:41.469 OC基础学习[674:21565] ---<SingeTest: 0x1003002f0>----<SingeTest: 0x1003002f0>-----+++-<SingeTest: 0x1003002f0>

Program ended with exit code: 0


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值