0% found this document useful (0 votes)
42 views7 pages

File Handling: Writing and Reading From Files

The document discusses file handling in iOS, including writing to files, reading from files, storing files in temporary folders, and creating/modifying property lists. It shows how to get the documents directory path, write and read strings to files, add new items to a property list stored in the documents directory, and read/write data to files on app launch/close.

Uploaded by

sowmidarling
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views7 pages

File Handling: Writing and Reading From Files

The document discusses file handling in iOS, including writing to files, reading from files, storing files in temporary folders, and creating/modifying property lists. It shows how to get the documents directory path, write and read strings to files, add new items to a property list stored in the documents directory, and read/write data to files on app launch/close.

Uploaded by

sowmidarling
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

File Handling

Writing and Reading from Files


#import <UIKit/UIKit.h> @interface FilesHandlingViewController : UIViewController { } -(NSString *) documentsPath; -(NSString *) readFromFile:(NSString *) filePath; -(void) writeToFile:(NSString *) text withFileName:(NSString *) filePath; @end

#import FilesHandlingViewController.h @implementation FilesHandlingViewController //---finds the path to the applications Documents directory---(NSString *) documentsPath { NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDir = [paths objectAtIndex:0]; return documentsDir; } //---write content into a specified file path---(void) writeToFile:(NSString *) text withFileName:(NSString *) filePath { NSMutableArray *array = [[NSMutableArray alloc] init]; [array addObject:text]; [array writeToFile:filePath atomically:YES]; [array release]; } //---read content from a specified file path---(NSString *) readFromFile:(NSString *) filePath { //---check if file exists--if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) { NSArray *array = [[NSArray alloc] initWithContentsOfFile: filePath]; NSString *data = [NSString stringWithFormat:@%@, [array objectAtIndex:0]]; [array release]; return data; } else return nil; } - (void)viewDidLoad { //---formulate filename--NSString *fileName = [[self documentsPath] stringByAppendingPathComponent:@data.txt]; //---write something to the file--[self writeToFile:@a string of text withFileName:fileName]; //---read it back--NSString *fileContent = [self readFromFile:fileName]; //---display the content read in the Debugger Console window--NSLog(@%@, fileContent); [super viewDidLoad]; }

Storing Files in the Temporary Folder


-(NSString *) tempPath{ return NSTemporaryDirectory(); }

The following statement returns the path of a fi le (data.txt) to be stored in the tmp folder:
NSString *fileName = [[self tempPath] stringByAppendingPathComponent:@data.txt];

Creating and Modifying a Property List

- (void)viewDidLoad { //---formulate filename--NSString *fileName = [[self documentsPath] stringByAppendingPathComponent:@data.txt]; //---write something to the file--[self writeToFile:@a string of text withFileName:fileName]; //---read it back--NSString *fileContent = [self readFromFile:fileName]; //---display the content read in the Debugger Console window--NSLog(@%@, fileContent); //---get the path to the property list file--NSString *plistFileName = [[self documentsPath] stringByAppendingPathComponent:@Apps.plist]; //---if the property list file can be found--if ([[NSFileManager defaultManager] fileExistsAtPath:plistFileName]) { //---load the content of the property list file into a NSDictionary // object--NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:plistFileName]; //---for each category--for (NSString *category in dict) { NSLog(@%@, category); NSLog(@========); //---return all titles in an array--NSArray *titles = [dict valueForKey:category]; //---print out all the titles in that category--for (NSString *title in titles) { NSLog(@%@, title); } } [dict release]; } else { //---load the property list from the Resources folder--NSString *pListPath = [[NSBundle mainBundle] pathForResource:@AppsofType:@plist]; NSDictionary *dict =[[NSDictionary alloc] initWithContentsOfFile:pListPath]; //---make a mutable copy of the dictionary object--NSMutableDictionary *copyOfDict = [dict mutableCopy];

//---get all the different categories--NSArray *categoriesArray =[[copyOfDict allKeys] sortedArrayUsingSelector:@selector(compare:)]; //---for each category--for (NSString *category in categoriesArray) { //---get all the app titles in that category--NSArray *titles = [dict valueForKey:category]; //---make a mutable copy of the array--NSMutableArray *mutableTitles = [titles mutableCopy]; //---add a new title to the category--[mutableTitles addObject:@New App title]; //---set the array back to the dictionary object--[copyOfDict setObject:mutableTitles forKey:category]; [mutableTitles release]; } //---write the dictionary to file--fileName = [[self documentsPath] stringByAppendingPathComponent:@Apps.plist]; [copyOfDict writeToFile:fileName atomically:YES]; [dict release]; [copyOfDict release]; } [super viewDidLoad]; }

#import <UIKit/UIKit.h> @interface FileExampleViewController : UIViewController { UITextField *textBox; UIButton *saveButton; } @property (nonatomic, retain) IBOutlet UITextField *textBox; - (IBAction)saveText:(id)sender; @end #import "FileExampleViewController.h" @implementation FileExampleViewController @synthesize textBox; - (void)saveText:(id)sender { NSFileManager *filemgr; NSData *databuffer; NSString *dataFile; NSString *docsDir; NSArray *dirPaths; filemgr = [NSFileManager defaultManager]; dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); docsDir = [dirPaths objectAtIndex:0]; dataFile = [docsDir stringByAppendingPathComponent: @"datafile.dat"]; databuffer = [textBox.text dataUsingEncoding: NSASCIIStringEncoding]; [filemgr createFileAtPath: dataFile contents: databuffer attributes:nil]; [filemgr release]; }

- (void)viewDidUnload {

// Release any retained subviews of the main view. // e.g. self.myOutlet = nil; self.textBox = nil; } - (void)dealloc { [textBox release]; [super dealloc]; } // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. - (void)viewDidLoad { NSFileManager *filemgr; NSString *dataFile; NSString *docsDir; NSArray *dirPaths; filemgr = [NSFileManager defaultManager]; // Identify the documents directory dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); docsDir = [dirPaths objectAtIndex:0]; // Build the path to the data file dataFile = [docsDir stringByAppendingPathComponent: @"datafile.dat"]; // Check if the file already exists if ([filemgr fileExistsAtPath: dataFile]) { // Read file contents and display in textBox NSData *databuffer; databuffer = [filemgr contentsAtPath: dataFile]; NSString *datastring = [[NSString alloc] initWithData: databuffer encoding:NSASCIIStringEncoding]; textBox.text = datastring; [datastring release]; }

[filemgr release]; [super viewDidLoad]; } @end

You might also like