[iOS] 从 application delegate 引伸三点

一、声明的 delegate 属性不老是 weak 策略

委托 delegationiOS 开发的经常使用设计模式,为了不对象与其代理之间的由于相互 retain 致使循环引用的发生,delegate 属性在现在的 ARC 时代一般声明为 weak 策略,然而在早期的手动管理内存的时代,还未引入 strong/weak 关键字,使用 assign 策略保证 delegate 的引用计数不增长, 在 Swift 中是 unowned(unsafe)UIApplicationdelegate 声明以下:git

// 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 手动设置为 nilgithub

@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 失效的两个方法:session

- (void)finishTasksAndInvalidate;
- (void)invalidateAndCancel;
复制代码

做为 NSURLSession 的第三方封装 AFNetworking,其 AFURLSessionManager 对应地提供了失效方法:app

/**
 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 时须要留意其声明方式,因地制宜地处理。ui

二、既然是 assign, 那么 AppDelegate 为何不会销毁

上文讨论 UIApplicationdelegate,也就是 AppDelegate 类的实例,其声明为 assign 策略,AppDelegate 实例没有其余对象引用,在应用的整个声明周期中是一直存在的,缘由是什么?atom

stackoverflow 的一个回答 Why system call UIApplicationDelegate's dealloc method? 中能够了解到一些状况,大意是:spa

  • 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]);
复制代码

三、使用 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瘦身的多种解决方案》

相关文章
相关标签/搜索