How can I discover the amount of free memory in iOS?
Asked
Active
Viewed 480 times
1
-
1What do you hope to accomplish? And how exactly do you define "free" memory? Since the OS can evict other processes at will, depending on what is needed, the right answer depends on your use case. – StilesCrisis Feb 27 '12 at 06:14
-
Possible duplication http://stackoverflow.com/questions/1020327/how-to-find-available-memory-in-iphone-programmatically – 0xDE4E15B Feb 27 '12 at 08:55
-
possible duplicate of [Available memory for iPhone OS app](http://stackoverflow.com/questions/2798638/available-memory-for-iphone-os-app) – dirkgently Jun 22 '12 at 06:31
2 Answers
1
Use this code:
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;
}
I'm not claiming credit for this code; I got it from here.
Hope this helps!
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;
}
This is working

Vijay
- 997
- 1
- 12
- 27