OC的懶加載
什么是懶加載:
懶加載——也稱為延遲加載,即在需要的時候才加載(效率低,占用內存小)。所謂懶加載,寫的是其get方法.
注意:如果是懶加載的話則一定要注意先判斷是否已經有了,如果沒有那么再去進行實例化。
懶加載的好處
(1)不必將創建對象的代碼全部寫在viewDidLoad方法中,代碼的可讀性更強
(2)每個控件的getter方法中分別負責各自的實例化處理,代碼彼此之間的獨立性強,松耦合
懶加載的例子:
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當中用的最多的一種模式。
實現單例模式有三個條件
1、類的構造方法是私有的
2、類提供一個類方法用於產生對象
3、類中有一個私有的自己對象
針對於這三個條件,OC中都是可以做到的
1、類的構造方法是私有的
我們只需要重寫allocWithZone方法,讓初始化操作只執行一次
2、類提供一個類方法產生對象
這個可以直接定義一個類方法
3、類中有一個私有的自己對象
我們可以在.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
總之單例的寫法就是這樣了,類方法里有一個自己的私有對象。