1、聲明的 delegate
屬性不總是 weak
策略
委托 delegation
是 iOS
開發的常用設計模式,為了避免對象與其代理之間的因為相互 retain 導致循環引用的發生,delegate
屬性在如今的 ARC
時代通常聲明為 weak
策略,然而在早期的手動管理內存的時代,還未引入 strong/weak
關鍵字,使用 assign
策略保證 delegate
的引用計數不增加, 在 Swift
中是 unowned(unsafe)
, UIApplication
的 delegate
聲明如下:
// OC
@property(nullable, nonatomic, assign) id<UIApplicationDelegate> delegate;
// Swift
unowned(unsafe) open var delegate: UIApplicationDelegate?
assign
和 weak
都只復制一份對象的指針,而不增加其引用計數,區別是:weak
的指針在對象釋放時會被系統自動設為 nil
,而 assign
卻仍然保存了 delegate
的舊內存地址,潛在的風險就是:如果 delegate
已銷毀,而對象再通過協議向 delegate
發送消息調用,則會導致野指針異常 exc_bad_access
,這在使用 CLLocationMananger
的 delegate
時尤其需要注意。如果使用了 delegate
為 assign
策略,則需要效仿系統對 weak
的處理,在 delegate
對象釋放時將 delegate
手動設置為 nil
。
@implementation XViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
[self.locationManager startUpdatingLocation];
}
/// 必須手動將其 delegate 設為 nil
- (void)dealloc {
[self.locationManager stopUpdatingLocation];
self.locationManager.delegate = nil;
}
@end
除了 assgin
的情況,還有一些情況下 delegate
是被對象強引用 retain
的,比如 NSURLSession
,delegate
將被 retain
到 session
對象失效為止。
/* .....
* If you do specify a delegate, the delegate will be retained until after
* the delegate has been sent the URLSession:didBecomeInvalidWithError: message.
*/
+ (NSURLSession *)sessionWithConfiguration:(NSURLSessionConfiguration *)config
delegate:(nullable id <NSURLSessionDelegate>)delegate
delegateQueue:(nullable NSOperationQueue *)queue;
對于這種情況,處理方式,循環引用是肯定存在的,解決的方式是通過移除引用的方式來手動打破,因此 NSURLSession
提供了 session
失效的兩個方法:
- (void)finishTasksAndInvalidate;
- (void)invalidateAndCancel;
作為 NSURLSession
的第三方封裝 AFNetworking
,其 AFURLSessionManager
對應地提供了失效方法:
/**
Invalidates the managed session, optionally canceling pending tasks.
@param cancelPendingTasks Whether or not to cancel pending tasks.
*/
- (void)invalidateSessionCancelingTasks:(BOOL)cancelPendingTasks;
此外,CAAnimation
的 delegate
也是 strong
引用,如果因為業務需要發生了循環引用,需要在合適的時機提前手動打破。
@interface CAAnimation
//...
/* The delegate of the animation. This object is retained for the
* lifetime of the animation object. Defaults to nil. See below for the
* supported delegate methods. */
@property(nullable, strong) id <CAAnimationDelegate> delegate;
總之,使用 delegate
時需要留意其聲明方式,因地制宜地處理。
2、既然是 assign
, 那么 AppDelegate
為什么不會銷毀
上文討論 UIApplication
對 delegate
,也就是 AppDelegate
類的實例,其聲明為 assign
策略,AppDelegate
實例沒有其他對象引用,在應用的整個聲明周期中是一直存在的,原因是什么?
在 stackoverflow
的一個回答 Why system call UIApplicationDelegate's dealloc method? 中可以了解到一些情況,大意是:
- 從
main.m
中初始化了第一個AppDelegate
實例,被系統內部隱式地retain
- 直到下一次
application
被賦值一個新的delegate
時系統才將第一個AppDelegate
實例釋放 - 對于新創建的
application
的delegate
對象,由創建者負責保證其不會立即銷毀,舉例如下:
// 聲明為靜態變量,長期持有
static AppDelegate *retainDelegate = nil;
/// 切換 application 的 delegate 對象
- (IBAction)buttonClickToChangeAppDelegate:(id)sender {
AppDelegate *delegate = [[AppDelegate alloc] init];
delegate.window.rootViewController = [[ViewController alloc] init];
[delegate.window makeKeyAndVisible];
retainDelegate = delegate;
[UIApplication sharedApplication].delegate = retainDelegate;
}
application
的 delegate
可以在必要時切換(通常不這樣做),UIApplication
單例的類型同樣是支持定制的,這個從 main.m
的啟動函數可以看出:
// If nil is specified for principalClassName,
// the value for NSPrincipalClass from the Info.plist is used. If there is no
// NSPrincipalClass key specified, the UIApplication class is used.
// The delegate class will be instantiated using init.
UIKIT_EXTERN int UIApplicationMain(int argc,
char *argv[],
NSString * __nullable principalClassName,
NSString * __nullable delegateClassName);
通過 UIApplicationMain()
函數傳參或者在 info.plist
中注冊特定的 key
值,自定義應用的 Application
和 AppDelegate
的類是可行的。
@interface XAppDelegate : UIResponder
@property (nonatomic, strong) UIWindow *window;
@end
@interface XApplication : UIApplication
@end
int main(int argc, char * argv[]) {
@autoreleasepool {
return UIApplicationMain(argc,
argv,
NSStringFromClass([XApplication class]),
NSStringFromClass([XAppDelegate class]));
}
}
又或者,干脆使用 runtime
在必要時將 application
對象替換為其子類。
/// runtime, isa-swizzling,置換應用單例的類為特定子類
object_setClass([UIApplication sharedApplication], [XApplication class]);
3、使用 Notification
和 category
避免 AppDelegate
的臃腫
因為 AppDelegate
是應用的 delegate
,其充當了應用內多個事件的監聽者,包括應用啟動、收到推送、打開 URL
、出入前后臺、收到通知、藍牙和定位等等。隨著項目的迭代,AppDelegate
將越發臃腫,因為 UIApplication
除了 delegate
外,還同時有發送很多通知 NSNotification
,因而可以從兩個方面去解決:
- 盡可能地通過
UIApplication
通知監聽來處理事件,比如應用啟動時會發送
UIApplicationDidFinishLaunchingNotification
通知 - 沒有通知但是特定業務的
UIApplicaiondDelegate
協議方法,可以按根據不同的業務類型,比如通知、openURL
分離到不同的AppDelegate
的category
中
進一步地,對于應用啟動時,就需要監聽的通知,合適時機是在某個特定類的 load
方法中開始。針對性地,可以為這種 Launch
監聽的情況進行封裝,稱為 AppLaunchLoader
:
- 在
AppLaunchLoader
的load
方法中監聽應用啟動的通知 - 在
AppLaunchLoader
的category
的load
方法中注冊啟動時需要執行的任務block
- 當監聽到應用啟動通知時執行注冊的所有
block
,完成啟動事件與AppDelegate
的分離。
typedef void(^GSLaunchWorker)(NSDictionary *launchOptions);
@interface GSLaunchLoader : NSObject
/// 注冊啟動時需要進行的配置工作
+ (void)registerWorker:(GSLaunchWorker)worker;
@end
@implementation GSLaunchLoader
+ (void)load {
NSNotificationCenter *c = [NSNotificationCenter defaultCenter];
[c addObserver:self selector:@selector(appDidLaunch:) name:UIApplicationDidFinishLaunchingNotification object:nil];
}
+ (void)appDidLaunch:(NSNotification *)notification {
[self handleLaunchWorkersWithOptions:notification.userInfo];
}
#pragma mark - Launch workers
static NSMutableArray <GSLaunchWorker> *_launchWorkers = nil;
+ (void)registerWorker:(GSLaunchWorker)worker { [[self launchWorkers] addObject:worker]; }
+ (void)handleLaunchWorkersWithOptions:(NSDictionary *)options {
for (GSLaunchWorker worker in [[self class] launchWorkers]) {
worker(options);
}
[self cleanUp];
}
+ (void)cleanUp {
_launchWorkers = nil;
NSNotificationCenter *c = [NSNotificationCenter defaultCenter];
[c removeObserver:self name:UIApplicationDidFinishLaunchingNotification object:nil];
}
+ (NSMutableArray *)launchWorkers {
if (!_launchWorkers) {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_launchWorkers = [NSMutableArray array];
});
}
return _launchWorkers;
}
@end
源代碼
推薦閱讀 蘇合的 《關于AppDelegate瘦身的多種解決方案》
加我微信溝通。