Monday, 22 June 2015

file handling in objective c

File Handling in Objective C

Before proceeding further read my last tutorials:Learn Objective C
The main task of many application is to create,save,update,delete data on files. 
If you are already familiar with IOS you know that data can be manage through database(sqlite),Core Data etc. Also local files can be used to store that useful information.
Final UI will be like as shown below:



What are files?

Anything arranged in Linear order one by one in incrementing pointer or sequential manner.
Data and files are stored in Secondary storage devices like floppy disk and hard disk.

How to handle files in IOS?

In IOS You are not directly linked with memory. Each Application has its own all folder. In general it acts like a container for all things.
You applcation has sandbox which contain documents,library,temp and Cloud related folder.


In general Each application has bundle from which it is installed like Application.app

Let take all directory overview:


1.)Application bundle: It contain all the resources needed to install application.You have only read only access to this folder and prevent from writing.

2.)Documents: It is used to contain storing user relating data.

3.)Temperary: It contain temporary files that having scope upto application open. When application close data is get lost.

4.) Library:This is directory is hidden to the user.It is used when no information is provide to General user.

NSFileManager is a class used to manage all files in IOS. It is the class resposible for organize all files in ios.

NSFileMAnager *manager=[NSFileMAnager defalultManager];


NSSearchPathForDirectoriesInDomain function is responsible managing path for accessing files. It has three parameters.

In first parameter there could be one of follwing according to need.
NSLibraryDirectory ,NSDocumentDirectory


IInd parameter is NSUserDomainMask.
3rd Parameter is boolean value to set If set to yes the path can be resolved automatocally.


This function returns path in the form of array.

NSArray *path=NSSearchPathForDirectoriesInDomain(NSDocumentsDirectory,NSUserDomainMAsk,YES);

//fetch all directories in document folder.


First value is root directory.


NSString *directory=[path objectatindex[0]];


NSManager has method contentsOfDirectoryAtPath message which returns the list of all files having it could be collection so NSArray used to fetch from it.

Load a file or Display Data

- (IBAction)displayData:(id)sender {

    NSArray *directory=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *rootpath=[directory objectAtIndex:0];
    rootpath=[rootpath stringByAppendingPathComponent:@"surajkamboj"];
    rootpath=[rootpath stringByAppendingPathComponent:@"hello.txt"];
    NSFileManager *manager=[NSFileManager defaultManager];
    if ([manager fileExistsAtPath:rootpath]) {
        NSData *file1=[[NSData alloc]initWithContentsOfFile:rootpath];
        NSString *string1=[[NSString alloc]initWithData:file1 encoding:NSASCIIStringEncoding];
        self.label.text=string1;
    }
    else{
        self.label.text=@"Error displaying data";
    }
}

Create Directory:

- (IBAction)createDirectory:(id)sender {
    NSError *error;
    NSArray *directory=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
    NSString *rootpath=[directory objectAtIndex:0]  ;
    NSFileManager *manager=[NSFileManager defaultManager];
    NSString *path=[rootpath stringByAppendingPathComponent:@"surajkamboj"];
    if(![manager fileExistsAtPath:path])
    {
        
        [manager createDirectoryAtPath:path withIntermediateDirectories:NO attributes:nil error:&error];
        self.label.text=@"Directory created successfully";
        
    }
    else
    {
       self.label.text=@"The error for creating directory.";
    }
    
}


Create File:

- (IBAction)createFile:(id)sender {
    NSArray *directory=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *rootpath=[directory objectAtIndex:0];
    NSFileManager *manager=[NSFileManager defaultManager];
    rootpath=[rootpath stringByAppendingPathComponent:@"surajkamboj"];
    NSString *path=[rootpath stringByAppendingPathComponent:@"hello.txt"];
    if (![manager fileExistsAtPath:path]) {
        NSData *data=@"I am suraj kamboj \nI am the IOS Developer";
        [manager createFileAtPath:path contents:data attributes:nil];
        self.label.text=@"File created successfully";
    }
    else{
        self.label.text=@"Error for creating File";
    }
    
    
    
    
}


Delete File:

- (IBAction)deleteFile:(id)sender {
    NSError *error;
    NSArray *directory=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *rootpath=[directory objectAtIndex:0];
    NSFileManager *manager=[NSFileManager defaultManager];
    rootpath=[rootpath stringByAppendingPathComponent:@"surajkamboj"];
    NSString *path=[rootpath stringByAppendingPathComponent:@"hello.txt"];
    if ([manager fileExistsAtPath:path])
    {
        [manager removeItemAtPath:path error:&error];
        self.label.text=@"File deleted successfully";
    }
    else{
        NSString *str=[NSString stringWithFormat:@"Error deleting file:%@",error];
        self.label.text=str;
    }

}


Rename File:

- (IBAction)renameFile:(id)sender {
    NSError *error;
    NSArray *directory=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *rootpath=[directory objectAtIndex:0];
    NSFileManager *manager=[NSFileManager defaultManager];
    rootpath=[rootpath stringByAppendingPathComponent:@"surajkamboj"];
    NSString *oldpath=[rootpath stringByAppendingPathComponent:@"hello.txt"];
    NSString *newPath=[rootpath stringByAppendingPathComponent:@"surajkamboj.txt"];
    if ([manager fileExistsAtPath:oldpath])
    {
        [manager moveItemAtPath:oldpath toPath:newPath error:&error];
        self.label.text=@"File Renamed successfully";
    }
    else{
        NSString *str=[NSString stringWithFormat:@"Error Renamed file:%@",error];
        self.label.text=str;
    }
}

Remember i have add static value but do not worry you can add values from text field UI control.It is also easy. I will write that tutorial lator when start IOS application development.


It is just output shown But how you see where are files if you want to get physically files from IOS simulator.

It is easy just unhide the hidden files first from mac. You can hide and unhide the files according to need. Search for unhidden files in mac. I am not teaching here to you Hacking. Files are hidden due to security reasons.

Go to User->your name->library(hidden)->developer->core simulator->devices->shows number of hashed folder select by checking which simulator you current run. 

then data->container->data->application->select your current running application data->then data.

document->You will see your made directory.








These are some output as shown below:



Source code available here:Download here

I hope you like my this tutorial. If you have any query you can mail me or comment here. I think all the topic related with objective c is covered if you want any other topic remains left tell me. I will try to publish here.

My next tutorial on IOS Application Devlopement With Objective C: Now available Click Here

1 comment: