在整個工程中(全局)需要使用其它類中的方法時,并且我們需要其它類中的數(shù)據(jù)(此時不能新創(chuàng)建這個類的對象,否則不能拿到數(shù)據(jù)),這個時候需要使用單例.
單例的使用
例如:在 BTLocationManager.h 中:
+ (instancetype)sharedManager;
.m中:
static BTLocationManager *_instance;
+ (instancetype)sharedManager {
NSLog(@"_instance= %@", _instance);
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
if (_instance == nil) {
_instance = [[self alloc]init];
}
});
return _instance;
}
// startLocate 方法
- (void)startLocate {
// 定位的方法
}
全局使用 BTLocationManager 類時,需要使用單例:
用單例調(diào)用 BTLocationManager 的方法
[[BTLocationManager sharedManager] startLocate];
用代碼解釋 '單例' 的作用
單例做的事情可以用另一種方式去解釋:如下
在你調(diào)用 startLocate 這個方法的時候?qū)懸粋€方法,然后在 BTLocationManager 中調(diào)用這個方法將 BTLocationManager 這個類創(chuàng)建的對象傳過來,例如:
我在 LBSManager這個類中需要使用到 BTLocationManager 這個類的對象,我需要將這個對象傳遞給 LBSManager ,首先在 BTLocationManager 創(chuàng)建一個對象,同時用全局變量記錄這個對象(否則出了這個方法就釋放了,在其它的類中就拿不到這個對象了):
BTLocationManager *locationManager = [[BTLocationManager alloc]init];
_locationManager = locationManager;
在 LBSManager.h 類中寫一個方法:
- (void)handleGlobalLocationManager:(BTLocationManager *)locationManager;
在 LBSManager.m
中實現(xiàn):
- (void)handleGlobalLocationManager:(BTLocationManager *)locationManager {
_locationManager = locationManager;
}
然后BTLocationManager
中調(diào)用,將:
LBSManager *lbsManager = [[LBSManager alloc]init];
[lbsManager handleGlobalLocationManager:_locationManager];
這樣就可以在 其LBSManager 類中調(diào)用 BTLocationManager 的方法了:如下
[_locationManager startLocate];
效果和單例一樣,這只是對單例的解釋
這時就可以在 LBSManager 中使用 BTLocationManager 的對象了,并且在這兩個類中只創(chuàng)建了一次 locationManager 對象,相當于單例的功能.
這樣完成一次全局的使用是相當麻煩的,所以單例的使用會很方便的讓我們在全局使用某個類,這個類的對象只需要創(chuàng)建一次,最好就是創(chuàng)建單例,否則可能會出錯(很可能會重復創(chuàng)建某個累的對象導致拿到的對象不是同一個,造成值傳遞為空的)或者比較繁瑣.