OC中的SingleTon

OC中的单例模式 比较Java中单例模式

需要重写 allocWithZone  确保使用的是同一块地址

重写copyWithZone 确定复制之后是同一个地址

 1 //
 2 //  SingleTon.m
 3 //  OCLearn8
 4 //
 5 //  Created by lyp on 16/7/10.
 6 //  Copyright © 2016年 awebing. All rights reserved.
 7 //
 8 
 9 #import "SingleTon.h"
10 static SingleTon *instance = nil;
11 
12 @interface SingleTon()
13 -(instancetype)init;
14 @end
15 
16 
17 @implementation SingleTon
18 
19 +(SingleTon*)getInstance {
20     if(instance == nil) {
21         instance = [[SingleTon alloc]init];
22     }
23     instance->_price = 100;
24     return instance;
25 }
26 
27 -(instancetype)init{
28     return self;
29 }
30 
31 
32 // 覆盖allocWithZone方法  确保使用的是同一块地址
33 +(id)allocWithZone:(struct _NSZone *)zone{
34     @synchronized (self) {
35         if(!instance) {
36             instance = [super allocWithZone:zone];
37             return instance;
38         }
39     }
40     return nil;
41 }
42 
43 -(id)copyWithZone:(NSZone *)zone; {
44     return self;
45 }
46 
47 @end

 

 

posted @ 2016-07-10 11:31  xadxxx  阅读(300)  评论(0编辑  收藏  举报