使用Xcode的Instruments调试内存泄漏
知识记录
- 使用Activity Monitor查看应用整体内存
- 使用Allocations查看应用内存分配
- 更改代码观察前后内存变化
Instruments-Activity Monitor
1. 打开项目中的Profile-Activity Monitor
- 注意:Xcode中Profile的使用必须要用自己的开发项目,需要以开发者的身份,不然会显示需要Develop的Certifacate。
- 推荐用Activity Monitor观察应用内存,虽然Allocations也可以看,但Activity Monitor更稳定,可以稳定运行6个小时。
首先测试真机连接电脑,点击Xcode->Product->Profile,选择Activity Monitor
2. 查看应用内存变化
先观察应用内存的整体变化趋势
可以将采集的数据保存在文件里。
Instruments-Allocations
1. 打开项目中的Profile-Allocations
2. 查看应用内存分配
点击左上角的圆点,开始数据采集。
修改Xcode中代码
找到UnityAppController.h,在开头添加#import <objc/runtime.h>
找到- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
在这个函数里面进行代码的修改,比如说在Allocations观察到MyPerformaneceInfo这个类的toJSONString函数有问题,我们可以在运行时替换掉toJSONString里面的方法,在函数的末尾添加:
Class myCls = NSClassFromString(@"MyPerformanceInfo");
Method originalMethod = class_getClassMethod(myCls, @selector(toJSONString:));
Method swizzledMethod = class_getClassMethod([self class],@selector(hookJSON:));
method_exchangeImplementations(originalMethod, swizzledMethod);
return YES;
在函数外面实现hookJSON的方法:
+ (NSString *)hookJSON:(id)jsonObj {
NSString *a = nil;
// @autoreleasepool {
if (jsonObj == nil) {
return nil;
}
if (![NSJSONSerialization isValidJSONObject:jsonObj]) {
return nil;
}
NSError *error;
NSData *data = [NSJSONSerialization dataWithJSONObject:jsonObj
options:0
error:&error];
NSUInteger size = [data length];
NSLog(@"size length:%@",@(size));
if (error || data==nil) {
return nil;
}
a = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//}
return a;
}
这样就实现了在运行时对代码的调试。