老生常谈 之 “AppDelegate瘦身”

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

背景

在iOS项目的开发中,AppDelegate是一个耦合发生的重灾地,很多项目的开发时间一长,AppDelegate就不可避免地出现,代码臃肿,调用顺序混乱,逻辑复杂的问题。

因此,可通过 AMKApplicationDelegate 无侵入的实现AppDelegate瘦身。

AppDelegate瘦身 之 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([AMKApplicationDelegate class]));
    }
}

如下是新方案与目前现有开源的解决方案的优劣势对比:

b3e88078de6729ac9e0a374bf0b450e68a5d998e.png

核心代码

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

AMKApplicationDelegate.h

//
//  AMKApplicationDelegate.h
//  AMKApplicationDelegate
//
//  Created by Meng,Xinxin on 2018/5/3.
//

#import <UIKit/UIKit.h>


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


/** 主ApplicationDelegate */
@protocol AMKMainApplicationDelegate <UIApplicationDelegate> @end

AMKApplicationDelegate.m

#import "AMKApplicationDelegate.h"


@interface AMKApplicationDelegate () @end

@implementation AMKApplicationDelegate

#pragma mark -- Properties --

@synthesize applicationDelegates = _applicationDelegates;

- (UIWindow *)window {
    return self.mainApplicationDelegate.window;
}

#pragma mark -- Public Methods --

+ (AMKApplicationDelegate *)sharedInstance {
    static AMKApplicationDelegate *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

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

@end

...

@implementation AMKApplicationDelegate (UIApplicationDelegate)

...

// 当应用程序启动完毕的时候就会调用(系统自动调用)
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(nullable NSDictionary<UIApplicationLaunchOptionsKey, id> *)launchOptions {
    BOOL flag = YES;
    for (id<UIApplicationDelegate> applicationDelegate in self.applicationDelegates) {
        if (![applicationDelegate respondsToSelector:@selector(application:didFinishLaunchingWithOptions:)]) continue;
        flag = flag && [applicationDelegate application:application didFinishLaunchingWithOptions:launchOptions];
    }
    return flag;
}

...

@end

使用

1. 引入

AMKApplicationDelegate 可通过CocoaPods完成引入,仅需现在工程的Podfile文件中 添加如下代码

pod 'AMKApplicationDelegate'

然后在终端在Podfile文件所在路径下执行 pod install命令即可完成源码下载与引入。

2. 接入

(1) 改写默认 AppDelegate

  • 改写 main.m 文件
@import UIKit;
#import "AMKAppDelegate.h"

int main(int argc, char * argv[]) {
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, NSStringFromClass(AMKApplicationDelegate.class));
    }
}

(2) 注册 主AppDelegate

  • 创建 AMKApplicationDelegate 的分类
// .h

#import <AMKApplicationDelegate/AMKApplicationDelegate.h>

@interface AMKApplicationDelegate (Demo) @end


// .m

#import "AMKApplicationDelegate+Demo.h"
#import "AMKAppDelegate.h"

@implementation AMKApplicationDelegate (Demo)

- (instancetype)init {
    if (self = [super init]) {
        NSMutableArray *applicationDelegates = [NSMutableArray array];
        [applicationDelegates addObject:AMKAppDelegate.new];
        self->_applicationDelegates = applicationDelegates;
    }
    return self;
}

@end
  • AMKAppDelegate.h 文件中实现 AMKMainApplicationDelegate 协议
#import "AMKApplicationDelegate.h"

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

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

3. 开发

如下是以 “添加 3D-Touch快捷方式” 为例,介绍如何横向扩展 AppDelegate。

(1) 创建管理类

  • AMKApplicationShortcutManager.h
#import <Foundation/Foundation.h>

/// 快捷方式
@interface AMKApplicationShortcutManager : NSObject <UIApplicationDelegate>

@end
  • AMKApplicationShortcutManager.m
#import "AMKApplicationShortcutManager.h"

NSString * const AMKApplicationShortcutItemTitleUserInfoKey = @"title";
NSString * const AMKApplicationShortcutItemMessageUserInfoKey = @"message";

@implementation AMKApplicationShortcutManager

/** 快捷入口 */
- (void)setupShortcutItems {
    if ([[UIApplication sharedApplication] respondsToSelector:@selector(shortcutItems)]) {
        NSMutableArray *shortcutItems = [NSMutableArray array];
        
        [shortcutItems addObject:({
            NSString *type = @"shortcutItem1";
            NSString *title = @"签到";
            NSString *subtitle = @"我是快捷操作描述";
            NSString *message = [NSString stringWithFormat:@"您点击了“%@”的快捷方式", title];
            
            NSMutableDictionary *userInfo = @{}.mutableCopy;
            userInfo[AMKApplicationShortcutItemTitleUserInfoKey] = title;
            userInfo[AMKApplicationShortcutItemMessageUserInfoKey] = message;
            
            UIApplicationShortcutItem *shortcutItem = [[UIApplicationShortcutItem alloc] initWithType:type localizedTitle:title localizedSubtitle:subtitle icon:[UIApplicationShortcutIcon iconWithTemplateImageName:@""] userInfo:userInfo];
            shortcutItem;
        })];
        
        [shortcutItems addObject:({
            NSString *type = @"shortcutItem2";
            NSString *title = @"查找";
            NSString *subtitle = @"我是快捷操作描述";
            NSString *message = [NSString stringWithFormat:@"您点击了“%@”的快捷方式", title];
            
            NSMutableDictionary *userInfo = @{}.mutableCopy;
            userInfo[AMKApplicationShortcutItemTitleUserInfoKey] = title;
            userInfo[AMKApplicationShortcutItemMessageUserInfoKey] = message;
            
            UIApplicationShortcutItem *shortcutItem = [[UIApplicationShortcutItem alloc] initWithType:type localizedTitle:title localizedSubtitle:subtitle icon:[UIApplicationShortcutIcon iconWithTemplateImageName:@""] userInfo:userInfo];
            shortcutItem;
        })];
        
        [UIApplication sharedApplication].shortcutItems = shortcutItems;
    }
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(nullable NSDictionary<UIApplicationLaunchOptionsKey, id> *)launchOptions {
    [self setupShortcutItems];
    return YES;
}

- (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler {
    NSString *title = [shortcutItem.userInfo objectForKey:AMKApplicationShortcutItemTitleUserInfoKey];
    NSString *message = [shortcutItem.userInfo objectForKey:AMKApplicationShortcutItemMessageUserInfoKey];
    [[[UIAlertView alloc] initWithTitle:title message:message delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
}

@end

(2) 注册

  • AMKApplicationDelegate+Demo.m 分类文件中注册新创建的管理类
#import "AMKApplicationDelegate+Demo.h"
#import "AMKApplicationShortcutManager.h"

@implementation AMKApplicationDelegate (Demo)

- (instancetype)init {
    if (self = [super init]) {
        NSMutableArray *applicationDelegates = [NSMutableArray array];
        [applicationDelegates addObject:AMKAppDelegate.new];
        [applicationDelegates addObject:AMKApplicationShortcutManager.new]; // 注册 3D-Touch快捷方式
        self->_applicationDelegates = applicationDelegates;
    }
    return self;
}

@end

执行结果

demo.gif

图片有点大,若加载失败 请前往如下地址查看:
https://github.com/AndyM129/AMKApplicationDelegate/blob/master/demo.gif

后话

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

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

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

“Stay hungry. Stay foolish.”

共勉~

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,569评论 4 363
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,499评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,271评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,087评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,474评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,670评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,911评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,636评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,397评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,607评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,093评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,418评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,074评论 3 237
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,092评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,865评论 0 196
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,726评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,627评论 2 270

推荐阅读更多精彩内容