最终内存值是根据各类内存(活跃,非活跃,联动,空闲)使用的页面数*单个页面大小所得。
#import <mach/mach.h> #import <mach/mach_host.h> - (NSString *)generateNumberFromValue:(unsigned long)originalValue { NSString * string = nil; double converteredValue = 0.0; if (originalValue >= 1000000000L) { converteredValue = originalValue / 1024.0 / 1024.0 / 1024.0; string = [NSString stringWithFormat:@"%.2lf GB Free", converteredValue]; } else { converteredValue = originalValue / 1024.0 /1024.0; string = [NSString stringWithFormat:@"%.0lf MB Free", converteredValue]; } return string; } - (NSDictionary *) generateMemoryInfo { mach_port_t host_port; mach_msg_type_number_t host_size; vm_size_t pagesize; host_port = mach_host_self(); host_size = sizeof(vm_statistics_data_t) / sizeof(integer_t); host_page_size(host_port, &pagesize); vm_statistics_data_t vm_stat; if (host_statistics(host_port, HOST_VM_INFO, (host_info_t)&vm_stat, &host_size) != KERN_SUCCESS) NSLog(@"Failed to fetch vm statistics"); /* Stats in bytes */ unsigned long mem_used = (vm_stat.active_count + vm_stat.inactive_count + vm_stat.wire_count) * (unsigned long)pagesize; unsigned long mem_free = vm_stat.free_count * (unsigned long)pagesize; unsigned long mem_total = (unsigned long)mem_used + (unsigned long)mem_free; NSLog(@"used: %ld free: %ld total: %ld pageSize: %ld", mem_used, mem_free, mem_total, pagesize); NSString * memoryUsedNumber = [self generateNumberFromValue:mem_used]; NSString * memoryFreeNumber = [self generateNumberFromValue:mem_free]; NSString * memoryTotalNumber = [self generateNumberFromValue:mem_total]; NSDictionary * dict = @{@"MemoryUsed":memoryUsedNumber, @"MemoryFree":memoryFreeNumber, @"MemoryTotal":memoryTotalNumber}; return dict; }