[关闭]
@qidiandasheng 2020-03-29T05:57:05.000000Z 字数 2502 阅读 1600

如何减少Appdelegate代码进行瘦身

iOS架构


FRDModuleManager

https://github.com/lincode/FRDModuleManager

这是豆瓣开发的一款 iOS 模块管理工具,可以减少Appdegate的代码。实现方式是注册各个模块,每一个模块实现UIApplicationDelegate对应的方法。最后由FRDModuleManager统一调用分发到各个模块。

  1. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  2. //注册实现UIApplicationDelegate对应方法的模块
  3. NSString* plistPath = [[NSBundle mainBundle] pathForResource:@"ModulesRegister" ofType:@"plist"];
  4. FRDModuleManager *manager = [FRDModuleManager sharedInstance];
  5. [manager loadModulesWithPlistFile:plistPath];
  6. //给个模块分发application:didFinishLaunchingWithOptions:方法
  7. [manager application:application didFinishLaunchingWithOptions:launchOptions];
  8. return YES;
  9. }
  10. - (void)applicationWillResignActive:(UIApplication *)application {
  11. [[FRDModuleManager sharedInstance] applicationWillResignActive:application];
  12. }

优点

缺点

JSDecoupledAppDelegate

https://github.com/JaviSoto/JSDecoupledAppDelegate

JSDecoupledAppDelegate通过拆分AppDelegate里面不同的方法类型来进行分开管理。

  1. @protocol JSApplicationStateDelegate;
  2. @protocol JSApplicationDefaultOrientationDelegate;
  3. @protocol JSApplicationBackgroundFetchDelegate;
  4. @protocol JSApplicationRemoteNotificationsDelegate;
  5. @protocol JSApplicationLocalNotificationsDelegate;
  6. @protocol JSApplicationStateRestorationDelegate;
  7. @protocol JSApplicationURLResourceOpeningDelegate;
  8. @protocol JSApplicationShortcutItemDelegate;
  9. @protocol JSApplicationHealthDelegate;
  10. @protocol JSApplicationProtectedDataDelegate;
  11. @protocol JSApplicationWatchInteractionDelegate;
  12. @protocol JSApplicationExtensionDelegate;
  13. @protocol JSApplicationActivityContinuationDelegate;

然后在main.m里把Appdelegate改为JSDecoupledAppDelegate

  1. return UIApplicationMain(argc, argv, nil, NSStringFromClass([JSDecoupledAppDelegate class]));

然后自己创建类来准守不同的协议进行代码的分拆。比如我要管理app生命周期相关的方法则遵守JSApplicationStateDelegate协议,然后再load时调用一下方法。

  1. + (void)load
  2. {
  3. [JSDecoupledAppDelegate sharedAppDelegate].appStateDelegate = [[self alloc] init];
  4. }

优点

缺点

使用它必须废弃原生的AppDelegate,因此我们不能通过((AppDelegate *)[UIApplication sharedApplication].delegate).window来获取windows,以及window的rootViewController。

通过AOP方式和通知来实现

https://github.com/jiaopen/AppDelegateExtensions

通过AOP的方式来Hook Appdelegate里面的方法,然后在方法里注册对应方法的通知,把方法通知出去。其他的类里面只要监听对应的通知即可。

通过Category

创建多个Appdelegate的Category,每个Category实现处理之前Appdelegate里不同的臃肿代码的方法。

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注