Thursday, September 6, 2012

Rename the file in the NSDocumentDirectory in an iOS application


This post will show how to rename a file located in the NSDocumentDirectory in an iOS application




NOTE: If you are still not confident about loading and saving the file in NSDcoumentDirectory then see this How to Load/Save a file from/to the NSDocumentDirectory in an iOS device

Lets declare a method -(void)renameFile; to do the renaming work


-(void)renameFile{
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString * oldPath =[[NSString alloc]init];
        NSString * newPath =[[NSString alloc]init];
        oldPath=[documentsDirectory stringByAppendingPathComponent:@"existing_file_name"];
        newPath=[documentsDirectory stringByAppendingPathComponent:@"new_file_name"];
        
        if ([fileManager fileExistsAtPath:oldPath]) {
            [fileManager moveItemAtPath:oldPath toPath:newPath error:nil];             
        }
}        

Here, oldPath is the path for your_file with existing file name and newPath is the path with new filename for the file that you want to rename. 
The main work is done by the method moveItemAtPathtoPatherror] which moves the file at oldPath to newPath

Suggestions and corrections are most welcome. If you have any, please do so without hesitation.

1 comment:

  1. The IOS is a best platform which provides great servicing and development of personalized enterprise app. Go with Ios application development training in Chennai to get indepth knowledge about IOS and its related application.

    ReplyDelete