[iOS] 從 application delegate 引申三點

1、聲明的 delegate 屬性不總是 weak 策略

委托 delegationiOS 開發的常用設計模式,為了避免對象與其代理之間的因為相互 retain 導致循環引用的發生,delegate 屬性在如今的 ARC 時代通常聲明為 weak 策略,然而在早期的手動管理內存的時代,還未引入 strong/weak 關鍵字,使用 assign 策略保證 delegate 的引用計數不增加, 在 Swift 中是 unowned(unsafe)UIApplicationdelegate 聲明如下:

// OC
@property(nullable, nonatomic, assign) id<UIApplicationDelegate> delegate;
// Swift
unowned(unsafe) open var delegate: UIApplicationDelegate?

assignweak 都只復制一份對象的指針,而不增加其引用計數,區別是:weak 的指針在對象釋放時會被系統自動設為 nil,而 assign 卻仍然保存了 delegate 的舊內存地址,潛在的風險就是:如果 delegate 已銷毀,而對象再通過協議向 delegate 發送消息調用,則會導致野指針異常 exc_bad_access,這在使用 CLLocationManangerdelegate尤其需要注意。如果使用了 delegateassign 策略,則需要效仿系統對 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 的,比如 NSURLSessiondelegate 將被 retainsession 對象失效為止。

/* .....
 * 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;

此外,CAAnimationdelegate 也是 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 為什么不會銷毀

上文討論 UIApplicationdelegate,也就是 AppDelegate 類的實例,其聲明為 assign 策略,AppDelegate 實例沒有其他對象引用,在應用的整個聲明周期中是一直存在的,原因是什么?

stackoverflow 的一個回答 Why system call UIApplicationDelegate's dealloc method? 中可以了解到一些情況,大意是:

  • main.m 中初始化了第一個 AppDelegate 實例,被系統內部隱式地 retain
  • 直到下一次 application 被賦值一個新的 delegate 時系統才將第一個 AppDelegate 實例釋放
  • 對于新創建的 applicationdelegate 對象,由創建者負責保證其不會立即銷毀,舉例如下:
// 聲明為靜態變量,長期持有
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;
}

applicationdelegate 可以在必要時切換(通常不這樣做),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 值,自定義應用的 ApplicationAppDelegate 的類是可行的。

@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、使用 Notificationcategory 避免 AppDelegate 的臃腫

因為 AppDelegate 是應用的 delegate,其充當了應用內多個事件的監聽者,包括應用啟動、收到推送、打開 URL、出入前后臺、收到通知、藍牙和定位等等。隨著項目的迭代,AppDelegate 將越發臃腫,因為 UIApplication 除了 delegate 外,還同時有發送很多通知 NSNotification,因而可以從兩個方面去解決:

  • 盡可能地通過 UIApplication 通知監聽來處理事件,比如應用啟動時會發送
    UIApplicationDidFinishLaunchingNotification 通知
  • 沒有通知但是特定業務的 UIApplicaiondDelegate 協議方法,可以按根據不同的業務類型,比如通知、openURL 分離到不同的 AppDelegatecategory

進一步地,對于應用啟動時,就需要監聽的通知,合適時機是在某個特定類的 load 方法中開始。針對性地,可以為這種 Launch 監聽的情況進行封裝,稱為 AppLaunchLoader

  • AppLaunchLoaderload 方法中監聽應用啟動的通知
  • AppLaunchLoadercategoryload 方法中注冊啟動時需要執行的任務 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

源代碼

點我去 GitHub 獲取源代碼,?鼓勵

推薦閱讀 蘇合的 《關于AppDelegate瘦身的多種解決方案》

加我微信溝通。


最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 1.ios高性能編程 (1).內層 最小的內層平均值和峰值(2).耗電量 高效的算法和數據結構(3).初始化時...
    歐辰_OSR閱讀 29,562評論 8 265
  • Swift1> Swift和OC的區別1.1> Swift沒有地址/指針的概念1.2> 泛型1.3> 類型嚴謹 對...
    cosWriter閱讀 11,136評論 1 32
  • OC語言基礎 1.類與對象 類方法 OC的類方法只有2種:靜態方法和實例方法兩種 在OC中,只要方法聲明在@int...
    奇異果好補閱讀 4,348評論 0 11
  • iOS面試題目100道 1.線程和進程的區別。 進程是系統進行資源分配和調度的一個獨立單位,線程是進程的一個實體,...
    有度YouDo閱讀 29,981評論 8 137
  • 微博上開啟#每天一個關鍵詞#斷斷續續,每日想寫又不想寫,想寫是因為想記錄,不想寫是因為就會一不小心就會把自己全部曝...
    韓小姐的城堡閱讀 106評論 0 0