`NSRealMemoryAvailable()` 已在 iOS 7+ 標記廢棄,雖仍可調用,但返回值僅為物理內存總量,無法區分 App 佔用/系統佔用/空閒,不符合現代監控需求。
#import
- (uint64_t)currentAppMemoryUsage {
mach_task_basic_info_data_t info;
mach_msg_type_number_t count = MACH_TASK_BASIC_INFO_COUNT;
kern_return_t kr = task_info(mach_task_self(),
MACH_TASK_BASIC_INFO,
(task_info_t)&info,
&count);
if (kr == KERN_SUCCESS) {
return info.resident_size; // 物理內存駐留大小 (bytes)
}
return 0;
}
#import
- (NSDictionary *)systemMemoryStats {
int mib[2] = {CTL_HW, HW_MEMSIZE};
uint64_t physicalMemory;
size_t len = sizeof(physicalMemory);
sysctl(mib, 2, &physicalMemory, &len, NULL, 0);
vm_statistics64_data_t vmStats;
mach_msg_type_number_t count = HOST_VM_INFO64_COUNT;
host_statistics64(mach_host_self(), HOST_VM_INFO64, (host_info64_t)&vmStats, &count);
uint64_t pageSize = vmStats.page_size;
uint64_t freeMem = vmStats.free_count * pageSize;
uint64_t activeMem = vmStats.active_count * pageSize;
uint64_t inactiveMem = vmStats.inactive_count * pageSize;
uint64_t wiredMem = vmStats.wire_count * pageSize;
return @{
@"total": @(physicalMemory),
@"free": @(freeMem),
@"active": @(activeMem),
@"inactive": @(inactiveMem),
@"wired": @(wiredMem),
@"appUsed": @([self currentAppMemoryUsage])
};
}