2012-08-27 27 views
3

可能重复:
How to Programmatically Tell How Much Memory an iOS App is Using?记忆的iPhone应用程序使用

我需要知道多少内存是由一个iPhone应用程序时,在前台或后台运行使用的应用程序。 如果每5秒显示内存使用率,它会更好。 是否可以编写代码来显示正在使用的内存? 任何建议将被appriciated

+0

为什么你不希望使用仪器来测试这一点,它的很多功能更强大和灵活,并避免将测试代码到你的实际项目。 – ikuramedia

回答

4

首先包括.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)); 
    } 
} 

方法.m文件

+1

在64位,iOS7上,这给出了疯狂的大数字,或0? – Adam

2

用户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)); 
    } 
} 
相关问题