码迷,mamicode.com
首页 > 其他好文 > 详细

手写单例singleton

时间:2015-11-23 13:27:12      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:

 

技术分享

 1 //
 2 //  ViewController.m
 3 //  singleton
 4 //
 5 //  Created by ys on 15/11/23.
 6 //  Copyright (c) 2015年 ys. All rights reserved.
 7 //
 8 
 9 
10 #import "ViewController.h"
11 #import "singletonClass.h"
12 
13 @interface ViewController ()
14 
15 @end
16 
17 @implementation ViewController
18 
19 - (void)viewDidLoad {
20     [super viewDidLoad];
21     
22     singletonClass *singleton1 = [[singletonClass alloc]init];
23     NSLog(@"---------%p",singleton1);
24     singletonClass *singleton2 = [[singletonClass alloc]init];
25     NSLog(@"---------%p",singleton2);
26     
27     NSLog(@"---------------------------------");
28     for (int i = 0; i<10; i++) {
29         singletonClass *singleton = [singletonClass sharedSingleton];
30         NSLog(@"---------%p",singleton);
31     }
32     
33 }
34 
35 
36 @end
37 
38 
39 //
40 ////
41 ////  singletonClass.m
42 ////  singleton
43 ////
44 ////  Created by ys on 15/11/23.
45 ////  Copyright (c) 2015年 ys. All rights reserved.
46 ////
47 //// 在iOS中,所有对象的内存空间的分配,最终都会调用allocWithZone方法
48 //// 如果要做单例,需要重写此方法
49 //// GCD提供了一个方法,专门用来创建单例的
50 ////因此手写单例一般步骤为:
51 ///**
52 // 1. 重写allocWithZone,用dispatch_once实例化一个静态变量
53 // 2. 写一个+sharedXXX方便其他类调用
54 // */
55 //
56 //
57 //#import "singletonClass.h"
58 //
59 //@implementation singletonClass
60 //
61 //+(instancetype)allocWithZone:(struct _NSZone *)zone
62 //{
63 //    static singletonClass *singleton;
64 //    static dispatch_once_t onceToken;
65 //    dispatch_once(&onceToken, ^{
66 //        singleton = [super allocWithZone:zone];
67 //    });
68 //    return singleton;
69 //}
70 //
71 //+(instancetype)sharedSingleton
72 //{
73 //    return [[self alloc]init];
74 //}
75 //@end

 

技术分享

手写单例singleton

标签:

原文地址:http://www.cnblogs.com/yangshun-work/p/4987882.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!