Manipulating Files

This task explains how to perform Finder-like operations on files using NSWorkspace.

Opening and Showing Files

NSWorkspace provides several methods for opening files:

To show a file in the Finder, use the selectFile:inFileViewerRootedAtPath: method.

Opening URLs

To open a URL with the default handler for the resource type, use the openURL: method. The URL can be either local or remote. For example, a local files are opened as if double-clicked in the Finder, and a web addresses are opened in the default web browser.

Performing File Operations

The NSWorkspace method performFileOperation:source:destination:files:tag: performs various file system operations on files, such as moving and copying. The following code fragment shows how to copy a file at fullPath from source to destination:

NSInteger tag;
BOOL succeeded;
NSString *source, *destination, *fullPath;    // Assume these exist
NSWorkspace *workspace = [NSWorkspace sharedWorkspace];
NSArray *files = [NSArray arrayWithObject:fullPath];
 
succeeded = [workspace performFileOperation:NSWorkspaceCopyOperation
                       source:source destination:destination
                       files:files tag:&tag];

In this code fragment, on return succeeded contains YES if the operation succeeded, NO otherwise. Also, the method sets tag to a negative integer if the operation fails, 0 if the operation is performed synchronously and succeeds, and a positive integer if the operation is performed asynchronously and succeeds.