1.技术痛点
在页面pop掉的时候, 这个页面会被释放掉, 否则会造成内存泄漏. 但此时如果网络慢, 已经起飞的网络请求还没返回落地, 页面就已经pop掉了,这显然是不合理的.又或是此时残留着上一个页面的HUD弹框不消失, 也不合理. 此时取消网络请求的办法有很多, 这里只说一下我的思路,无代码入侵,全局监控,一键火化,很舒服.
2.实现
① 创建一个UINavigationController的Category
#import <UIKit/UIKit.h>
@interface UINavigationController (YMInstance)
@end
② 利用的是runtime中的方法交换method_exchangeImplementations
#import "UINavigationController+YMInstance.h"
#import <objc/runtime.h>
@implementation UINavigationController (YMInstance)
+ (void)load{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
//原始系统方法
Method originalPopFunc = class_getInstanceMethod(self, @selector(popViewControllerAnimated:));
//我的方法
Method newPopFunc = class_getInstanceMethod(self, @selector(newPopFunc));
//方法交换
method_exchangeImplementations(originalPopFunc, newPopFunc);
});
}
- (void)newPopFunc{
[self newPopFunc];
/*
...
UINavigationController的每一次popViewControllerAnimated动作在这里都会被捕获, 你可以在这里做你想做的任何事.
1.取消未落地网络请求(我的所有NSURLSessionTask装在一个数组里, 此时在子线程for循环cancel掉)
2.打印骚包日志
3.去掉苟延残喘的HUD弹框
...
your code
...
*/
}
@end
3.启发
可以利用这个思路对比如UIViewController的生命周期方法进行替换, 打印骚包日志, 方便调试(Tencent的MLeaksFinder核心就是基于这个原理) .又或者是对UILabel之类的UI控件进行全局的设置, 屏幕适配爽歪歪, 实现一键火化需求...都是可以的. 希望能给你一点小小的启发 .
网友评论