iPhone开发之内存监测代码实现

新建一个继承NSObject的类ICMemoryHelper,.m文件的代码如下所示:

#import "ICMemoryHelper.h"
#import "AppDelegate.h"
#include <sys/sysctl.h>
#include <mach/mach.h>

@implementation ICMemoryHelper
//可用内存
+(double)availableMemory
{
    vm_statistics_data_t vmStats;
    mach_msg_type_number_t infoCount = HOST_VM_INFO_COUNT;
    kern_return_t kernReturn = host_statistics(mach_host_self(),HOST_VM_INFO,(host_info_t)&vmStats,&infoCount);
    if(kernReturn != KERN_SUCCESS)
    {
        return NSNotFound;
    }
    return ((vm_page_size * vmStats.free_count) / 1024.0) / 1024.0;
}

//已用内存
+(double)usedMemory
{
    task_basic_info_data_t taskInfo;
    mach_msg_type_number_t infoCount = TASK_BASIC_INFO_COUNT;
    kern_return_t kernReturn = task_info(mach_task_self(),
                                         TASK_BASIC_INFO, (task_info_t)&taskInfo, &infoCount);
    if(kernReturn != KERN_SUCCESS) {
        return NSNotFound;
    }
    return taskInfo.resident_size / 1024.0 / 1024.0;
}

//输出内存
+(void)OutputMemory {
    DebugLog(@"the memory use now is %f the available %f",[self usedMemory],[self availableMemory]);
}
@end

 

调用的时候只要:[ICMemoryHelper OutputMemory];就可以了

posted @ 2012-08-20 09:36  小、  阅读(1033)  评论(0编辑  收藏  举报