標籤:
#include <mach/mach.h>
//儲存記憶體
- (float)getFreeDiskspace{
float totalSpace;
float totalFreeSpace=0.f;
NSError *error = nil;
NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSDictionary *dictionary = [[NSFileManagerdefaultManager] attributesOfFileSystemForPath:[pathslastObject] error: &error];
if (dictionary) {
NSNumber *fileSystemSizeInBytes = [dictionary objectForKey: NSFileSystemSize];
NSNumber *freeFileSystemSizeInBytes = [dictionaryobjectForKey:NSFileSystemFreeSize];
totalSpace = [fileSystemSizeInBytesfloatValue]/1024.0f/1024.0f/1024.0f;
totalFreeSpace = [freeFileSystemSizeInBytesfloatValue]/1024.0f/1024.0f/1024.0f;
NSLog(@"Memory Capacity of %f GB with %f GB Free memory available.", totalSpace, totalFreeSpace);
}else {
NSLog(@"Error Obtaining System Memory Info: Domain = %@, Code = %@", [errordomain], [errorcode]);
}
return totalFreeSpace;
}
//可用運行記憶體
- (double)getAvailableBytes
{
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) + (vmStats.inactive_count * vm_page_size);
}
- (double)getAvailableKiloBytes
{
return [selfgetAvailableBytes] / 1024.0;
}
- (double)getAvailableMegaBytes
{
return [selfgetAvailableKiloBytes] / 1024.0;
}
//-----------------------------------------------------
記憶體各種類型
原文網址http://www.cnblogs.com/bandy/archive/2012/08/15/2639742.html
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
);
}
}
調用memoryInfo()就能拿到記憶體資訊了,它的類型是vm_statistics_data_t。這個結構體有很多欄位,在logMemoryInfo()中展示了如何擷取它們。注意這些欄位大都是頁面數,要乘以vm_page_size才能拿到位元組數。
順便再簡要介紹下:free是空閑記憶體;active是已使用,但可被分頁的(在iOS中,只有在磁碟上靜態存在的才能被分頁,例如檔案的記憶體映射,而動態分配的記憶體是不能被分頁的);inactive是不活躍的,也就是程式退出後卻沒釋放的記憶體,以便加快再次啟動,而當記憶體不足時,就會被回收,因此也可看作空閑記憶體;wire就是已使用,且不可被分頁的。
最後你會發現,即使把這些全加起來,也比裝置記憶體少很多,那麼剩下的只好當成已被佔用的神秘記憶體了。不過在模擬器上,這4個加起來基本上就是Mac的實體記憶體量了,相差不到2MB。
而總實體記憶體可以用NSRealMemoryAvailable()來擷取,這個函數不需要提供參數,文檔裡也有記載,我就不寫示範代碼了。
IOS代碼擷取記憶體大小