Get Total and Free Space on the Mounted File System

I recently was writing code to manage the download and storing of mp4 files to enable an application to play movies off-line. One consideration when dealing with files of significant size (50-100 megs) is disk space availability – this tip shows the method I called to get information about the mounted file system.

Get Free Disk Space

To get free space available, the class NSFileManager provides a method attributesOfFileSystemForPath:error: which will return a dictionary that includes five entries with various file system information.

// Get access to a file manager as our means
// to perform file operations
NSFileManager *fileManager = [NSFileManager defaultManager];
// Using the application home directory, get dictionary of attributes
NSDictionary *attributesDict = [fileManager attributesOfFileSystemForPath:NSHomeDirectory() error:NULL];
// Print total file system size and available space  
NSLog(@"File system size: %lld", [[attributesDict objectForKey:NSFileSystemSize] longLongValue]);
NSLog(@"File system free space: %lld", [[attributesDict objectForKey:NSFileSystemFreeSize] longLongValue]);

Notice that the objects for the keys requested are NSNumbers. Calling the method longLongValue returns the value of the object as a long long type, which I use to print information to console.

For information on the additional attributes in the dictionary, check out the NSFileManager API documenation.

Comments are closed.