Wednesday, September 5, 2012

How to Load/Save a file from/to the NSDocumentDirectory in an iOS application

This post is about loading and saving a file from and to the NSDocumentDirectory in an iOS application

Here we will declare two methods:-
-(void)loadFile; // to read file form the NSDocumentDirectory
-(void)saveFile; // to store file to the NSDocumentDirectory



Let us use an example of a .plist file named "your_file" which you hav created or added in your, lets say, Supporting Files folder in your xcode project. Lets use NSDictionary selectedObjectsDict to store the fetched .plist file.


NSDictionary * selectedObjectsDict;

-(void)loadPlistFile{
    BOOL success;
    NSError *error;
    NSString *filePath= [[NSBundle mainBundle] pathForResource:@"your_file" ofType:@"plist"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString * path =[[NSString alloc] initWithString:
                                      [documentsDirectory stringByAppendingPathComponent:@"your_file.plist"]];
    
    success = [fileManager fileExistsAtPath:path];
    if (success) {
        self.selectedObjectsDict=[[NSMutableDictionary alloc] initWithContentsOfFile:path];       
        
    }
    else
    {    
        
        success = [fileManager copyItemAtPath:filePath  toPath:path error:&error];
        self.selectedObjectsDict=[[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
        
        
    }    
    
}

Here, filePath stores the path of your_file in your Xcode folder (not the path in NSDocumentDirectory). fileManager is a NSFileManager object which help you to perform many generic file-system operations for you. paths stores the array of strings which defines the path for different directories in domainsdocumentsDirectory stores the path for Documents directory which is the first object in the array pathsFinally, path stores the path to the file "your_file" which will be inside the Documents directory
Now the if else function checks if the file has already been saved to the Document directory. If TRUE is loads the selectedObjectsDict with the file your_file in Document directory else it copies the file your_file from filePath (i.e. the path for folder in the Xcode project) to path(i.e. the path for the NSDocumentDirectory ) and also loads the selectedObjectsDict with the same file.

Saving the file to the NSDocumentDirectory is almost similar and much easier. You just need to have the path where you want to save the file. The main work is done by the method-[file_to_be_saved writeToFile: path_to_be_used_to_save atomically:YES];



-(void)savePlistFile{
    [self.selectedObjectsDict setObject:self.selectedObjectsArray forKey:self.objectUID];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString * path =[[NSString alloc] initWithString:
                                      [documentsDirectory stringByAppendingPathComponent:@"your_file.plist"]];
    [self.selectedObjectsDict writeToFile:path atomically:YES];
}


However, some may wants to rename the file in the directory. See this Rename the file in the NSDocumentDirectory



1 comment:

  1. Hi,

    Thank you for sharing this coding, given both the coding is quite helpful and error free. You shared in details about the coding which is also efficient with the ios code review tools

    ReplyDelete