Writing and appending data to files in iOS

If we want to create a file in iOS and write a lot of something there, we should firstly use NSFileManager class to create a file and then NSFileHandle class to write and append data. NSFileHandle class lets to append data to file and manage files more precisely, while NSFileManager class is simpler and lets to create and manage files and folders.

Firstly, we get a path to Documents directory(folder) and make a full file name:

NSArray *paths = NSSearchPathForDirectoriesInDomains
 (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSLog(@"%@",documentsDirectory);
//make a full file name
NSString *fileName = [NSString stringWithFormat:@"%@/yourFileName.txt", documentsDirectory];
NSLog(@"File path and name:%@", fileName);

Then we create an instance of NSFileManager class and check, if the file exists of not. And if not, then we create a file:

NSFileManager *filemgr;
filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: fileName ] == YES)
 NSLog (@"File exists");
else
{
 NSLog (@"File not found");
 [filemgr createFileAtPath:fileName contents:nil attributes:nil];
}

Then we create an instance of NSFileHandle class to write and append data. We also convert NSString to NSData, since we can write only NSData to file. We also append \n to write each next record on a separate line. After we finish working with file, we should close it.

NSFileHandle *myHandle = [NSFileHandle fileHandleForWritingAtPath:fileName];
if (myHandle == nil)
 NSLog(@"Failed to open file");
NSString *content;
NSData *theData;
for (int i=0; i less 100, i++) {
 content = [NSString stringWithFormat:@"%d\n"
 NSLog(@"content: %@", content);
 theData=[content dataUsingEncoding:NSUTF8StringEncoding];
 [myHandle seekToEndOfFile];
 [myHandle writeData:theData];
}
[myHandle closeFile];

To find out a file, you should add a parameter “Application supports iTunes file sharing” to Info-Plist file, then look at your application’s files in iTunes. If you use Simulator, then you should go to Finder, press Go or Shift+Cmd+G and type ~/Library, then go to Application Support/iPhone Simulator/5.0/Applications/Some number/Documents.

References and useful links:

Leave a Reply

Your email address will not be published. Required fields are marked *