Skip to content

Instantly share code, notes, and snippets.

@songxing10000
Created November 11, 2016 16:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save songxing10000/1ba568d9f3d4ad12640be9b2c189e8e5 to your computer and use it in GitHub Desktop.
Save songxing10000/1ba568d9f3d4ad12640be9b2c189e8e5 to your computer and use it in GitHub Desktop.
viewDidAppear打印当前页面类名,dealloc时打印销毁画页,看是否有离开未销毁可能存在内存泄漏的页面
#import <UIKit/UIKit.h>
/**
viewDidAppear打印当前页面类名,dealloc时打印销毁画页,看是否有离开未销毁可能存在内存泄漏的页面
*/
@interface UIViewController (Hook)
@end
#import "UIViewController+Hook.h"
#import <objc/runtime.h>
#ifdef DEBUG
#if 0 // 0 详细输出 1 简洁输出
#define SXLog(FORMAT, ...) fprintf(stderr,"\n文件:\t%s\t 行数: %d 方法:\t%s \n输出:\t%s\n",[[[NSString stringWithUTF8String:__FILE__] lastPathComponent] UTF8String], __LINE__,__FUNCTION__, [[NSString stringWithFormat:FORMAT, ##__VA_ARGS__] UTF8String]);
#else
#define SXLog(FORMAT, ...) fprintf(stderr,"%s\n", [[NSString stringWithFormat:FORMAT, ##__VA_ARGS__] UTF8String]);
#endif
#else
#define SXLog(...)
#endif
@implementation UIViewController (Hook)
//静态就交换静态,实例方法就交换实例方法
void Swizzle_(Class c, SEL origSEL, SEL newSEL)
{
Method origMethod = class_getInstanceMethod(c, origSEL);
Method newMethod = nil;
if (!origMethod) {
origMethod = class_getClassMethod(c, origSEL);
if (!origMethod) {
return;
}
newMethod = class_getClassMethod(c, newSEL);
if (!newMethod) {
return;
}
}else{
newMethod = class_getInstanceMethod(c, newSEL);
if (!newMethod) {
return;
}
}
//自身已经有了就添加不成功,直接交换即可
if(class_addMethod(c, origSEL, method_getImplementation(newMethod), method_getTypeEncoding(newMethod))){
class_replaceMethod(c, newSEL, method_getImplementation(origMethod), method_getTypeEncoding(origMethod));
}else{
method_exchangeImplementations(origMethod, newMethod);
}
}
#ifdef DEBUG
+ (void)load {
static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{
Class class = [self class];
// 进入画页,快速定位当前要修改的页面名字
Swizzle_(class, NSSelectorFromString(@"viewDidAppear:"), @selector(myViewDidAppear:));
// 画页销毁,是否存在不释放现象
Swizzle_(class, NSSelectorFromString(@"dealloc"), @selector(myDealloc));
});
}
- (void)myViewDidAppear:(BOOL)animated {
SXLog(@"----进入画页%@---", [self class]);
[self myViewDidAppear:animated];
}
- (void)myDealloc {
SXLog(@"----销毁画页%@---", [self class]);
[self myDealloc];
}
#endif
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment