Write row data on iphone

I can write to a text file on iphone .. but every time I write my previous value, it is deleted, is there a way to keep records separated by \ n ??

this is my code

NSString * cc=@ "1"; [cc writeToFile:storePath atomically:YES]; NSString *myText1 = [NSString stringWithContentsOfFile:storePath]; NSLog(@"text is %@",myText1); 

it gives me 1 now i want to add 2 as 1 and then 2

+4
source share
4 answers

Use the NSFileHandle seekToEndOfFile method and call writeData

 NSFileHandle *aFileHandle; NSString *aFile; aFile = [NSString stringWithString:@"Your File Path"]; //setting the file to write to aFileHandle = [NSFileHandle fileHandleForWritingAtPath:aFile]; //telling aFilehandle what file write to [aFileHandle truncateFileAtOffset:[aFileHandle seekToEndOfFile]]; //setting aFileHandle to write at the end of the file [aFileHandle writeData:[toBeWritten dataUsingEncoding:nil]]; //actually write the data 
+7
source

Here is a method of the NSString category that will add a receiver to the specified path with the specified encoding (usually NSUTF8StringEncoding).

 - (BOOL) appendToFile:(NSString *)path encoding:(NSStringEncoding)enc; { BOOL result = YES; NSFileHandle* fh = [NSFileHandle fileHandleForWritingAtPath:path]; if ( !fh ) { [[NSFileManager defaultManager] createFileAtPath:path contents:nil attributes:nil]; fh = [NSFileHandle fileHandleForWritingAtPath:path]; } if ( !fh ) return NO; @try { [fh seekToEndOfFile]; [fh writeData:[self dataUsingEncoding:enc]]; } @catch (NSException * e) { result = NO; } [fh closeFile]; return result; } 
+2
source

I don’t fully understand the question, but you can try every time you save the text, first read the text already in the file, then use stringByAppendingString. For example, the code

 NSString *begRainbow = @"Red orange yellow green"; NSString *fullRainbow = [begRainbow stringByAppendingString:@" blue purple"]; 

FullRainbow leaves with the value "Red Orange Yellow Green Blue Purple".

-2
source

Add entire file contained in NSMutableArray, then Write Every time Add to array An Write this

-2
source

All Articles