Sunday, April 21, 2013

NSFileManager copyItemAtPath example ios


copyItemAtPath :toPath:error:

Copies the item at the specified path to a new location synchronously.
- (BOOL)copyItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError**)error
Parameters
srcPath
The path to the file or directory you want to move. This parameter must not be nil.
dstPath
The path at which to place the copy of srcPath. This path must include the name of the file or directory in its new location. This parameter must not be nil.
error
On input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify nil for this parameter if you do not want the error information.
Return Value of [NSFileManager copyItemAtPath]
YES if the item was copied successfully or the file manager’s delegate aborted the operation deliberately. Returns NO if an error occurred.
Discussion of [NSFileManager copyItemAtPath]
When copying items, the current process must have permission to read the file or directory at srcPath and write the parent directory of dstPath. If the item at srcPath is a directory, this method copies the directory and all of its contents, including any hidden files. If a file with the same name already exists at dstPath, this method aborts the copy attempt and returns an appropriate error. If the last component of srcPath is a symbolic link, only the link is copied to the new path.
Prior to copying an item, the file manager asks its delegate if it should actually do so for each item. It does this by calling the fileManager:shouldCopyItemAtURL:toURL: method; if that method is not implemented it calls the fileManager:shouldCopyItemAtPath:toPath: method instead. If the delegate method returns YES, or if the delegate does not implement the appropriate methods, the file manager copies the given file or directory. If there is an error copying an item, the file manager may also call the delegate’s fileManager:shouldProceedAfterError:copyingItemAtURL:toURL: orfileManager:shouldProceedAfterError:copyingItemAtPath:toPath: method to determine how to proceed.
Example of [NSFileManager copyItemAtPath]

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    NSString* src = @"/Users/xxxxxxx/Desktop/testdir/a.dat";
    NSString* target = @"/Users/xxxxxxx/Desktop/readonlyfilecopy/testdir/a.dat";
    NSError* error = nil;

    [[NSFileManager defaultManager] copyItemAtPath:src toPath:target error:&error];

    if (error) {
        NSLog(@"%@", error);
        NSLog(@"%@", [error userInfo]);
    }

    [pool drain];
    return 0;
}