我需要知道iPhone应用程序在前台或后台运行时使用了多少内存。最好每5秒钟显示一次内存使用情况。是否有可能编写代码来显示正在使用的内存?欢迎任何建议。
首先在.h文件中包含report_memory方法,然后进行导入操作。
#import <mach/mach.h>
把这个写到.m文件里
然后在你想要打印内存使用值的地方写入这行代码
[NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(report_memory) userInfo:nil repeats:YES];
-(void) report_memory {
struct task_basic_info info;
mach_msg_type_number_t size = sizeof(info);
kern_return_t kerr = task_info(mach_task_self(),
TASK_BASIC_INFO,
(task_info_t)&info,
&size);
if( kerr == KERN_SUCCESS ) {
NSLog(@"Memory usage: %.4lf MB", info.resident_size/1024.0/1024.0);
} else {
NSLog(@"Error with task_info(): %s", mach_error_string(kerr));
}
}
用户NSTimer被安排在每5秒运行一次。以下是获取已使用内存值的代码:
#import <mach/mach.h>
void report_memory(void) {
struct task_basic_info info;
mach_msg_type_number_t size = sizeof(info);
kern_return_t kerr = task_info(mach_task_self(),
TASK_BASIC_INFO,
(task_info_t)&info,
&size);
if( kerr == KERN_SUCCESS ) {
NSLog(@"Memory in use (in bytes): %u", info.resident_size);
} else {
NSLog(@"Error with task_info(): %s", mach_error_string(kerr));
}
}