【发布时间】:2018-04-12 06:35:14
【问题描述】:
我正在开发需要获取应用程序生命周期事件的框架。我正在尝试使用 NotificationCenter 它在框架下失败。所以我决定使用 obj c 运行时来实现 Method Swizzling。问题是以下代码在 Emulator 中正常工作。当我运行设备时它失败了。
好消息是扩展方法被调用,当调用原始方法时,这会失败并显示消息
Thread 1: EXC_BAD_ACCESS (code=1, address=0x20)
这是我的代码
IMP originalImplementation;
+ (instancetype)initWith:(NSString *)bundleIdentifier{
Demo *instance = [[Demo alloc] init];
[instance swizzlingLifeCycleMethods];
return instance;
}
- (void)swizzlingLifeCycleMethods{
//Prepare the injected class name to be injecting
Class originalClass = NSClassFromString(@"AppDelegate");
//Prepare the methods to swizzling
SEL originalWillResignAction = @selector(applicationWillResignActive:);
SEL extendedWillResignActive = NSSelectorFromString(@"extendedApplicationWillResignActive");
//Get original method and method encoding
originalResignMethod = class_getInstanceMethod(originalClass, originalWillResignAction);
originalImplementation = method_getImplementation(originalResignMethod);
const char *originalResignMethodEncoding = method_getTypeEncoding(originalResignMethod);
//Add swizzling method into targetted class
class_addMethod(originalClass, extendedWillResignActive, (IMP)extendedApplicationWillResignActive, originalResignMethodEncoding);
//Swizzling the methods
Method extendedResignMethod = class_getInstanceMethod(originalClass, extendedWillResignActive);
method_exchangeImplementations(originalResignMethod, extendedResignMethod);
}
//Called at the time of user enters into background
void extendedApplicationWillResignActive(id self, SEL _cmd, va_list args1)
{
//Implement our logic here
//Call the original function after our stuff done
((void(*)(id, SEL, ...))originalImplementation)(self, _cmd, args1);
}
我在我的示例项目中使用通用框架构建来使用这个框架。请让我知道这有什么问题。
【问题讨论】:
标签: ios objective-c runtime