Because the memory of mobile devices such as the iPhone is limited and the swap zone cannot be used, in order not to cause insufficient memory and cause lower running efficiency or application crash, sometimes you need to obtain the current memory status, to determine the cache policy.
However, this underlying API is not mentioned in the iOS SDK documentation, so I searched for it and found the host_statistics () function.
Although there are many parameters, they are basically fixed values, so I will not explain them. I will directly go to the Code:
- #include <mach/mach.h>
-
- BOOL memoryInfo(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);
-
- return kernReturn == KERN_SUCCESS;
- }
-
- void logMemoryInfo() {
- vm_statistics_data_t vmStats;
-
- if (memoryInfo(&vmStats)) {
- NSLog(@"free: %u\nactive: %u\ninactive: %u\nwire: %u\nzero fill: %u\nreactivations: %u\npageins: %u\npageouts: %u\nfaults: %u\ncow_faults: %u\nlookups: %u\nhits: %u",
- vmStats.free_count * vm_page_size,
- vmStats.active_count * vm_page_size,
- vmStats.inactive_count * vm_page_size,
- vmStats.wire_count * vm_page_size,
- vmStats.zero_fill_count * vm_page_size,
- vmStats.reactivations * vm_page_size,
- vmStats.pageins * vm_page_size,
- vmStats.pageouts * vm_page_size,
- vmStats.faults,
- vmStats.cow_faults,
- vmStats.lookups,
- vmStats.hits
- );
- }
- }
Call memoryInfo () to obtain the memory information. Its type is vm_statistics_data_t. This struct has many fields and shows how to obtain them in logMemoryInfo. Note that most of these fields are the number of pages. You must multiply vm_page_size to get the number of bytes.
By the way, let's briefly introduce: free memory is idle; active memory is used, but can be paged (in iOS, only static storage on the disk can be paged, for example, the File Memory ing, And the dynamically allocated memory cannot be paged); inactive is inactive. In fact, when the memory is insufficient, your application can seize this part of memory, therefore, it can also be seen as idle memory; wire is used and cannot be paged.
In the end, you will find that even if you add up all the memory, it is much less than the device memory, so the rest will be treated as the occupied mysterious memory. However, in the simulator, the four are basically the physical memory of the Mac, with a difference of less than 2 MB.
The total physical memory can be obtained using NSRealMemoryAvailable (). This function does not need to provide parameters and is recorded in the document. I will not write the Demo code.