iOS开发iOS学习

老生常谈 之 “AppDelegate瘦身”

2018-05-03  本文已影响6人  Andy__M

本文原文地址:http://www.jianshu.com/p/ab7d05f53c1e
代码地址:https://github.com/AndyM129/AMKApplicationDelegate

前言

“AppDelegate瘦身” 真的是一个老生常谈的话题了,之所以再次提起,是因为我在刷博客时,偶然间看到这样一段内容:

图片

看完这段精辟的见解后,我真的是有一种 久旱逢甘露 的感觉啊,为什么自己就早没想到呢 —— 在参与开发的若干项目中,每一个项目的AppDelegate真可谓是 没有最臃肿,只有更臃肿,虽然通过 分类 做了些许优化,但效果都不是很理想:

思考

在理解了上图的思想后,我没有盲目的动手Coding,而是打开Github,键入AppDelegate,搜一遍看看有什么现有的好的实现~~

其中,《DelegateDietDemo - AppDelegate瘦身指南Demo》 (另可见原文)对目前常见的方案做了一个梳理,但我觉得都不足够好:

所以,我想了另外一种方案,更准确的说,是几种方案的结合:

  1. 将之前的每一个分类都改为一个独立的代理类,以处理该模块中App在各生命周期的事项
  2. 通过一个管理类来代替原有的AppDelegate,使得该管理类可以分发生命周期的各方法到对应代理类
  3. 在若干代理类中标记一个主代理,做一些统筹,或UIWindow的实例化等操作
  4. main.m文件中,改用代理类
int main(int argc, char * argv[]) {
    @autoreleasepool {
        // 之前的用法
        // return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
    
        // 改用 管理类
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([BDEApplicationDelegate class]));
    }
}

核心代码

注:该项目在 Xcode Version 9.2 上开发,目标支持iOS8+,没有测试更早的iOS版本。

AMKApplicationDelegate.h/m

/** 主ApplicationDelegate */
@protocol BDEMainApplicationDelegate @end

/** ApplicationDelegate 解耦 */
@interface BDEApplicationDelegate : NSObject <UIApplicationDelegate> {
    @protected NSArray<id<UIApplicationDelegate>> *_applicationDelegates;
}
@property(nonatomic, strong, readonly) NSArray<id<UIApplicationDelegate>> *applicationDelegates;
@property(nonatomic, strong, readonly) id<UIApplicationDelegate> mainApplicationDelegate;
@end



@implementation BDEApplicationDelegate

@synthesize applicationDelegates = _applicationDelegates;

- (id<UIApplicationDelegate>)mainApplicationDelegate {
    static id<UIApplicationDelegate> mainApplicationDelegate = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        // 查找主代理
        for (id<UIApplicationDelegate> applicationDelegate in self.applicationDelegates) {
            if ([applicationDelegate conformsToProtocol:@protocol(BDEMainApplicationDelegate)]) {
                // 断言
                NSAssert(mainApplicationDelegate==nil, @"`BDEMainApplicationDelegate` 协议的实现类有且仅有一个");
                
                // 赋值主代理
                mainApplicationDelegate = applicationDelegate;
            }
        }
        
        // 主代理有效性判断
        NSAssert(mainApplicationDelegate!=nil, @"`BDEMainApplicationDelegate` 协议的实现类有且仅有一个");

    });
    return mainApplicationDelegate;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(nullable NSDictionary<UIApplicationLaunchOptionsKey, id> *)launchOptions {
    BOOL flag = YES;
    for (id<UIApplicationDelegate> applicationDelegate in self.applicationDelegates) {
        if (![applicationDelegate respondsToSelector:_cmd]) continue;
        flag = flag && [applicationDelegate application:application didFinishLaunchingWithOptions:launchOptions];
    }
    return flag;
}

@end

UIApplication+AMKApplicationDelegate.h/m

因为在main.m文件中改用AMKApplicationDelegate类后,[UIApplication sharedApplication].delegate也会变成AMKApplicationDelegate的实例,为了做到 无侵入 原有代码逻辑,这里需要将delegate重定向为AMKApplicationDelegate主代理

@interface UIApplication (BDEApplicationDelegate)
@end

@implementation UIApplication (BDEApplicationDelegate)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        void (^__method_swizzling)(SEL, SEL) = ^(SEL sel, SEL _sel) {
            Method  method = class_getInstanceMethod(self, sel);
            Method _method = class_getInstanceMethod(self, _sel);
            method_exchangeImplementations(method, _method);
        };
        __method_swizzling(@selector(delegate), @selector(BDEApplicationDelegate_delegate));
    });
}

- (id<UIApplicationDelegate>)BDEApplicationDelegate_delegate {
    id<UIApplicationDelegate> delegate = [self BDEApplicationDelegate_delegate];
    if ([delegate isKindOfClass:BDEApplicationDelegate.class]) {
        delegate = ((BDEApplicationDelegate *)delegate).mainApplicationDelegate;
    }
    return delegate;
}

@end

用法

举例各模块代理类

#import "BDEAppDelegate.h"

@interface BDEUserNotificationAppDelegate : UIResponder<UIApplicationDelegate> 
@end

@implementation BDEUserNotificationAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    NSLog(@"加载配置:用户通知");
    return YES;
}

@end
#import "BDEAppDelegate.h"

@interface BDELanuchAdAppDelegate : UIResponder<UIApplicationDelegate>
@end

@implementation BDELanuchAdAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    NSLog(@"加载配置:开屏广告");
    return YES;
}

@end

AMKAppDelegate.h/m

主代理类核心不用改,只需添加AMKMainApplicationDelegate协议即可:

#import <AMKApplicationDelegate/AMKApplicationDelegate.h>

@interface AMKAppDelegate : UIResponder <UIApplicationDelegate, AMKMainApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end

@implementation AMKAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor redColor];
    self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController:AMKViewController.new];
    [self.window makeKeyAndVisible];
    NSLog(@"加载配置:主代理");
    return YES;
}
@end

初始化AMKApplicationDelegate

@implementation BDEApplicationDelegate (Demo)

- (instancetype)init {
    if (self = [super init]) {
        self->_applicationDelegates = @[BDEAppDelegate.new, BDELanuchAdAppDelegate.new, BDEUserNotificationAppDelegate.new];
    }
    return self;
}

@end

注:AMKApplicationDelegate本身没有去干预App生命周期方法中,各代理类的调用顺序,直接以初始化的顺序调用,使用者可以按需初始化~

执行结果

2018-05-03 19:55:37.038561+0800 BDEApplicationDelegate_Example[18316:506836] 加载配置:主代理
2018-05-03 19:55:37.038985+0800 BDEApplicationDelegate_Example[18316:506836] 加载配置:开屏广告
2018-05-03 19:55:37.039442+0800 BDEApplicationDelegate_Example[18316:506836] 加载配置:用户通知

后话

本文原文地址:http://www.jianshu.com/p/ab7d05f53c1e
代码地址:https://github.com/AndyM129/AMKApplicationDelegate

如果你有好的 idea 或 疑问,请随时提 issue 或 request。

如果你在开发过程中遇到什么问题,或对iOS开发有着自己独到的见解,再或是你与我一样同为菜鸟,都可以关注或私信我的微博。

“Stay hungry. Stay foolish.”

共勉~

上一篇 下一篇

猜你喜欢

热点阅读