(Object-C)学习笔记 --OC的懒加载和单例方法

OC的懒加载设计模式

  什么是懒加载:服务器

    懒加载——也称为延迟加载,即在须要的时候才加载(效率低,占用内存小)。所谓懒加载,写的是其get方法.atom

    注意:若是是懒加载的话则必定要注意先判断是否已经有了,若是没有那么再去进行实例化。spa

  懒加载的好处设计

    (1)没必要将建立对象的代码所有写在viewDidLoad方法中,代码的可读性更强code

    (2)每一个控件的getter方法中分别负责各自的实例化处理,代码彼此之间的独立性强,松耦合对象

  懒加载的例子:blog

 1 #import "MusicTableViewController.h"
 2 #import "TRMusicGroup.h"
 3 
 4 @interface MusicTableViewController ()
 5 
 6 @property(nonatomic,strong)TRMusicGroup *group;
 7 
 8 @end
 9 
10 
11 @implementation MusicTableViewController
12 
13 - (TRMusicGroup *)group
14 {
15     if (!_group) {
16         _group = [TRMusicGroup fakeData][0];
17     }
18     return _group;
19 }

 

 

OC的单例方法进程

  单例模式,也叫 单子模式,是一种经常使用的软件设计模式。在应用这个模式时,单例对象的类必须保证只有一个实例存在。许多时候整个系统只须要拥有一个的全局对象,这样有利于咱们协调系统总体的行为。好比在某个服务器程序中,该服务器的配置信息存放在一个文件中,这些配置数据由一个单例对象统一读取,而后服务进程中的其余对象再经过这个单例对象获取这些配置信息。这种方式简化了在复杂环境下的配置管理。
  单例模式多是OC当中用的最多的一种模式。

实现单例模式有三个条件内存

一、类的构造方法是私有的

二、类提供一个类方法用于产生对象

三、类中有一个私有的本身对象

 

针对于这三个条件,OC中都是能够作到的

一、类的构造方法是私有的

咱们只须要重写allocWithZone方法,让初始化操做只执行一次

二、类提供一个类方法产生对象

这个能够直接定义一个类方法

三、类中有一个私有的本身对象

咱们能够在.m文件中定义一个属性便可

看一下普通方法写单例:

TRStudent.h

1 #import <Foundation/Foundation.h>
2 
3 @interface TRStudent : NSObject
4 //属性
5 @property (nonatomic, strong) NSArray *stuArray;
6 //单例方式一
7 + (id)sharedStudent;
8 @end

 

TRStudent.m
 1 #import "TRStudent.h"
 2 
 3 @implementation TRStudent
 4 
 5 static TRStudent *_student = nil;
 6 + (id)sharedStudent {
 7     if (!_student) {
 8         //初始化实例对象Instance Object
 9         _student = [[TRStudent alloc] init];
10     }
11     return _student;
12 }
13 
14 - (NSArray *)stuArray {
15     if (!_stuArray) {
16         _stuArray = @[@"shirley", @"bob"];
17     }
18     return _stuArray;
19 }
20 
21 //重写alloc方法,完善单例的建立
22 + (instancetype)alloc {
23     //父类的alloc方法/返回一个单例对象
24     if (!_student) {
25         _student = [super alloc];
26     }
27     return _student;
28 }
29 //有的书会重写这个方法
30 //+ (instancetype)allocWithZone:(struct _NSZone *)zone {
31 //    
32 //}
33 
34 @end

 

15年以后大部分都用GCD来写单例:

TRStuden.h

1 #import <Foundation/Foundation.h>
2 
3 @interface TRStudent : NSObject
4 
5 //使用gcd一次性任务建立单例
6 + (id)sharedStudentByGCD;
7 
8 @end

 

TRStuden.m
 1 #import "TRStudent.h"
 2 
 3 @implementation TRStudent
 4 
 5 static TRStudent *_studentByGCD = nil;
 6 + (id)sharedStudentByGCD {
 7 
 8     static dispatch_once_t onceToken;
 9     dispatch_once(&onceToken, ^{
10         _studentByGCD = [[TRStudent alloc] init];
11     });
12     
13     return _studentByGCD;
14 }
15 
16 //重写alloc方法
17 + (instancetype)alloc {
18     static dispatch_once_t onceToken;
19     dispatch_once(&onceToken, ^{
20         _studentByGCD = [super alloc];
21     });
22     
23     return _studentByGCD;
24 }
25 
26 @end

 

总之单例的写法就是这样了,类方法里有一个本身的私有对象。
相关文章
相关标签/搜索