如何发现iOS中的可用内存量?

时间:2012-02-27 06:09:48

标签: ios

如何发现iOS中的可用内存量?

2 个答案:

答案 0 :(得分:1)

使用此代码:

natural_t  freeMemory(void) {
    mach_port_t           host_port = mach_host_self();
    mach_msg_type_number_t   host_size = sizeof(vm_statistics_data_t) / sizeof(integer_t);
    vm_size_t               pagesize;
    vm_statistics_data_t     vm_stat;

    host_page_size(host_port, &pagesize);

    if (host_statistics(host_port, HOST_VM_INFO, (host_info_t)&vm_stat, &host_size) != KERN_SUCCESS) NSLog(@"Failed to fetch vm statistics");

    natural_t   mem_used = (vm_stat.active_count + vm_stat.inactive_count + vm_stat.wire_count) * pagesize;
    natural_t   mem_free = vm_stat.free_count * pagesize;
    natural_t   mem_total = mem_used + mem_free;

    return mem_free;
}

我没有声称这个代码;我是从here得到的。

希望这有帮助!

答案 1 :(得分:1)

- (uint64_t)getFreeDiskspace
{
uint64_t totalSpace = 0;
uint64_t totalFreeSpace = 0;

__autoreleasing error = nil;  
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);  
NSDictionary *dictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:[paths lastObject] error: &error];  

if (dictionary) {  
    NSNumber *fileSystemSizeInBytes = [dictionary objectForKey: NSFileSystemSize];  
    NSNumber *freeFileSystemSizeInBytes = [dictionary objectForKey:NSFileSystemFreeSize];
    totalSpace = [fileSystemSizeInBytes unsignedLongLongValue];
    totalFreeSpace = [freeFileSystemSizeInBytes unsignedLongLongValue];
    NSLog(@"Memory Capacity of %llu MiB with %llu MiB Free memory available.", ((totalSpace/1024ll)/1024ll), ((totalFreeSpace/1024ll)/1024ll));
} else {  
    NSLog(@"Error Obtaining System Memory Info: Domain = %@, Code = %d", [error domain], [error code]);  
}  

return totalFreeSpace;
}

这是有效的