标签:
OC的懒加载
什么是懒加载:
懒加载——也称为延迟加载,即在需要的时候才加载(效率低,占用内存小)。所谓懒加载,写的是其get方法.
注意:如果是懒加载的话则一定要注意先判断是否已经有了,如果没有那么再去进行实例化。
懒加载的好处
(1)不必将创建对象的代码全部写在viewDidLoad方法中,代码的可读性更强
(2)每个控件的getter方法中分别负责各自的实例化处理,代码彼此之间的独立性强,松耦合
懒加载的例子:
#import "MusicTableViewController.h" #import "TRMusicGroup.h" @interface MusicTableViewController () @property(nonatomic,strong)TRMusicGroup *group; @end @implementation MusicTableViewController - (TRMusicGroup *)group { if (!_group) { _group = [TRMusicGroup fakeData][0]; } return _group; }
OC的单例方法
实现单例模式有三个条件
1、类的构造方法是私有的
2、类提供一个类方法用于产生对象
3、类中有一个私有的自己对象
针对于这三个条件,OC中都是可以做到的
1、类的构造方法是私有的
我们只需要重写allocWithZone方法,让初始化操作只执行一次
2、类提供一个类方法产生对象
这个可以直接定义一个类方法
3、类中有一个私有的自己对象
我们可以在.m文件中定义一个属性即可
看一下普通方法写单例:
TRStudent.h
#import <Foundation/Foundation.h> @interface TRStudent : NSObject //属性 @property (nonatomic, strong) NSArray *stuArray; //单例方式一 + (id)sharedStudent; @end
TRStudent.m
#import "TRStudent.h" @implementation TRStudent static TRStudent *_student = nil; + (id)sharedStudent { if (!_student) { //初始化实例对象Instance Object _student = [[TRStudent alloc] init]; } return _student; } - (NSArray *)stuArray { if (!_stuArray) { _stuArray = @[@"shirley", @"bob"]; } return _stuArray; } //重写alloc方法,完善单例的创建 + (instancetype)alloc { //父类的alloc方法/返回一个单例对象 if (!_student) { _student = [super alloc]; } return _student; } //有的书会重写这个方法 //+ (instancetype)allocWithZone:(struct _NSZone *)zone { // //} @end
15年之后大部分都用GCD来写单例:
TRStuden.h
#import <Foundation/Foundation.h> @interface TRStudent : NSObject //使用gcd一次性任务创建单例 + (id)sharedStudentByGCD; @end
TRStuden.m
#import "TRStudent.h" @implementation TRStudent static TRStudent *_studentByGCD = nil; + (id)sharedStudentByGCD { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _studentByGCD = [[TRStudent alloc] init]; }); return _studentByGCD; } //重写alloc方法 + (instancetype)alloc { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _studentByGCD = [super alloc]; }); return _studentByGCD; } @end
总之单例的写法就是这样了,类方法里有一个自己的私有对象。
标签:
原文地址:http://www.cnblogs.com/firstaurora/p/5185827.html