xcode在发布初就提供Insruments供我们内存调试,在这里我简单介绍下Instruments在xcode4下的使用,该文以xcode4.3.1作为范本。
编写一个单页面工程,命名为Memleak,为了便于测试内存泄露,这里选取两个函数,一个是对传统的C 中char* 字符数组的内存泄露,另一个是对object-C下 NSMutableArray 类的泄露。先贴上代码:
MemLeakViewController.h
#import <UIKit/UIKit.h>
@interface MemLeakViewController : UIViewController
@end
MemLeakViewController.m
#import "MemLeakViewController.h"
@interface MemLeakViewController ()
- (void) leakCstring;
- (void) leakArray;
@end
@implementation MemLeakViewController
- (void) leakCstring
{
UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"String mem leak testing" message:@"You try to leak string memory" delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil];
[alert show];
char* leakstring = malloc(sizeof(char)*128);
leakstring = NULL;
[alert release];
}
- (void) leakArray
{
UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"Array mem leak testing" message:@"You try to leak Arr memory" delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil];
[alert show];
NSArray *leakarray = [ [NSMutableArray alloc] init ];
leakarray = nil;
[alert release];
}
- (void)viewDidLoad
{
/* 显示标题 */
[super viewDidLoad];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 160)];
label.textAlignment = UITextAlignmentCenter;
label.text = @"This is mem leak testing!";
[self.view addSubview:label];
[label release];
/* 泄露字符串按钮 */
UIButton *button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button1 setTitle:@"Leak Cstring" forState:UIControlStateNormal];
[button1 setFrame:CGRectMake(20, 160, 120, 30)];
[button1 addTarget:self action:@selector(leakCstring) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button1];
/* 泄露NSMutableArray按钮 */
UIButton *button2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button2 setTitle:@"Leak Array" forState:UIControlStateNormal];
[button2 setFrame:CGRectMake(20, 300, 120, 30)];
[self.view addSubview:button2];
[button2 addTarget:self action:@selector(leakArray) forControlEvents:UIControlEventTouchUpInside];
}
编译通过后在顶端的Xcode标签下选择Open Developer Tool 从菜单里选择Instruments,Instruments 工具集里包含了各种牛逼闪闪的调试工具。
选取内存泄露检测工具Leaks,可以看看到如下界面:
点击左上角的“Choose Target”选取调试的目标文件。一般xcode 生成的目标文件存储在/users/用户名/library/Developer/Xcode/DeriveData中,注意在添加目标文件前先编译一次,生成目标文件。运行Record按钮,如下图所示:
正常运行程序,同时会出现以时间为坐标的内存监测进度。分别点击“Leak Cstring”和“Leak Array”。在一定时延下会在Leaks 坐标中出现黄色竖条,其高度是泄露内存的大小。在下侧的 Leaked Object可以参看具体的信息,包括泄露内存大小和地址。