//
// 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