iPhone应用程序所使用的内存

3
我需要知道iPhone应用程序在前台或后台运行时使用了多少内存。最好每5秒钟显示一次内存使用情况。是否有可能编写代码来显示正在使用的内存?欢迎任何建议。

为什么你不想使用Instruments来测试呢?它更加强大和灵活,避免了将测试代码放入你的实际项目中。 - ikuramedia
2个回答

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));
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接