Skip to content

Instantly share code, notes, and snippets.

@klaus01
Created January 16, 2019 03:35
Show Gist options
  • Save klaus01/eeeb970803d01bfddf11bcb15da7c7da to your computer and use it in GitHub Desktop.
Save klaus01/eeeb970803d01bfddf11bcb15da7c7da to your computer and use it in GitHub Desktop.
使用 Runtime 消息转发,实现 AppDelegate 中的代码模块化。
//
// AppDelegate.h
// TestMethod
//
// Created by 柯磊 on 2019/1/2.
// Copyright © 2019 AMonster. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
//
// AppDelegate.m
// TestMethod
//
// Created by 柯磊 on 2019/1/2.
// Copyright © 2019 AMonster. All rights reserved.
//
#import "AppDelegate.h"
@import ObjectiveC;
@interface AppDelegate1 : NSObject <UIApplicationDelegate>
@end
@implementation AppDelegate1
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSLog(@"AppDelegate1 - didFinishLaunchingWithOptions");
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application {
NSLog(@"AppDelegate1 - applicationWillResignActive");
}
@end
@interface AppDelegate2 : NSObject <UIApplicationDelegate>
@end
@implementation AppDelegate2
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSLog(@"AppDelegate2 - didFinishLaunchingWithOptions");
return YES;
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
NSLog(@"AppDelegate2 - applicationDidBecomeActive");
}
@end
@interface AppDelegate ()
@property (nonatomic, strong) NSArray<id<UIApplicationDelegate>> *delegates;
@end
@implementation AppDelegate
- (NSArray<id<UIApplicationDelegate>> *)delegates {
if (!_delegates) {
_delegates = @[[AppDelegate1 new], [AppDelegate2 new]];
}
return _delegates;
}
- (BOOL)respondsToSelector:(SEL)aSelector {
BOOL ret = [super respondsToSelector:aSelector];
if (ret) {
return ret;
}
for (id<UIApplicationDelegate> delegate in self.delegates) {
if ([delegate respondsToSelector:aSelector]) {
return YES;
}
}
return NO;
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
for (NSObject *delegate in self.delegates) {
if ([delegate respondsToSelector:aSelector]) {
return [delegate methodSignatureForSelector:aSelector];
}
}
return [super methodSignatureForSelector:aSelector];
}
- (void)forwardInvocation:(NSInvocation *)anInvocation {
SEL sel = anInvocation.selector;
BOOL isExec = NO;
for (NSObject *delegate in self.delegates) {
if ([delegate respondsToSelector:sel]) {
[anInvocation invokeWithTarget:delegate];
isExec = YES;
}
}
if (!isExec) {
[self doesNotRecognizeSelector:sel];
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment