Information about Files and Volumes

This article describes how you can get and set information about files and volumes.

Getting and Setting File Attributes

In Mac OS X v10.6 and later, you can use NSURL to get and set attributes of the item the URL points to. There are two methods to get attribute values and two methods to set attribute values, to get or set a single value, or to get or set multiple values simultaneously:

NSURL also defines constants for the keys to specify the attributes, including for example NSURLNameKey, NSURLLocalizedNameKey, NSURLIsPackageKey, NSURLCreationDateKey, NSURLFileSizeKey, and NSURLCustomIconKey.

The following examples show how you can get and set single and multiple attributes:

NSURL *url = <#Get a URL#>;
NSError *error = nil;
BOOL ok;
 
// Get the item's label color
NSColor *labelColor;
ok = [url getResourceValue:&labelColor forKey:NSURLLabelColorKey error:&error];
if (!ok) {
    // Handle the error.
}
 
// Make the item hidden
ok = [url setResourceValue:[NSNumber numberWithBool:YES] forKey:NSURLIsHiddenKey error:&error];
if (!ok) {
    // Handle the error.
}
 
// Get numerous properties
NSArray *keys = [NSArray arrayWithObjects:NSURLNameKey, NSURLLocalizedNameKey,
                                          NSURLIsRegularFileKey, NSURLIsDirectoryKey,
                                          NSURLIsSymbolicLinkKey, NSURLIsPackageKey, nil];
NSDictionary *properties = [url resourceValuesForKeys:keys error:&error];
if (properties == nil) {
    // Handle the error.
}

Getting Information about Volumes

In Mac OS X v10.6 and later, you can find out about the volumes mounted on the system using mountedVolumeURLsIncludingResourceValuesForKeys:options:. The method returns an array of NSURL objects containing the resource values corresponding to the keys you specify (if you simply want to find out what volumes are present, you can pass nil for the keys argument). The options argument allows you to specify whether you want to omit hidden volumes, and whether the method should return file reference URLs (see Creating File Reference URLs).

The following examples shows how to get, for all the available volumes, URLs including the localized name and the default icon:

NSArray *resourceKeys = [NSArray arrayWithObjects:
                          NSURLLocalizedNameKey, NSURLEffectiveIconKey, nil];
NSArray *volumeURLs = [[NSFileManager defaultManager]
                         mountedVolumeURLsIncludingResourceValuesForKeys:resourceKeys
                         options:0];