![]()
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
![]()