【问题标题】:Memory used by iPhone app [duplicate]iPhone应用程序使用的内存[重复]
【发布时间】:2012-08-27 17:35:54
【问题描述】:

可能重复:
How to Programmatically Tell How Much Memory an iOS App is Using?

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

【问题讨论】:

  • 你为什么不想使用 Instruments 来测试它,它更强大、更灵活,并且避免将测试代码放入你的实时项目中。

标签: iphone ios ios5 memory


【解决方案1】:

首先在.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 文件的方法

【讨论】:

  • 在 64 位 iOS7 上,这给出了非常大的数字,还是 0?
【解决方案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));
    }
}

【讨论】:

    猜你喜欢
    • 2014-11-23
    • 2011-05-09
    • 2013-07-18
    • 1970-01-01
    • 2012-03-25
    • 2011-01-03
    • 2011-06-30
    相关资源
    最近更新 更多