Nandagopal T
Nandagopal T

Reputation: 2037

Write data to a file without removing the old contents in iPhone

I want to write data to a .txt file without replacing its older contents.I have moved the file from the NSMainBundle to the documents directory.I am able to write the the file by using the code

NSData *data=[NSKeyedArchiver archivedDataWithRootObject:recentMainArray];
NSFileHandle *myHandle = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
[myHandle seekToEndOfFile];
[myHandle writeData:data];
[myHandle closeFile];

But when i try to display the contents of the file,i don't have any data in that.File exists in that path also.This is the following code i use to display the contents.

NSFileManager *manager = [NSFileManager defaultManager];

//filePath - > the documents directory file path

if([manager fileExistsAtPath:filePath]) {

        NSMutableArray *savedArray = [[NSMutableArray alloc] initWithContentsOfFile:filePath];
        NSMutableArray *storedRecentID = [savedArray objectAtIndex:0];
        NSMutableArray *storedRecentName = [savedArray objectAtIndex:1];
        NSLog(@"ID:%@",[savedArray objectAtIndex:0]);
        NSLog(@"Name:%@",[savedArray objectAtIndex:1]);

} 
else {
        NSLog(@"file not found, save something to create the file");
}

"null" which is printed as result for those two nslogs.

Please anybody let me know a solution for this problem.FYI,i am using a simulator to test,is this creating a problem.Please suggest me a solution.I have searched a lot and i am not able to find a solution.

Thank you all in advance

Upvotes: 0

Views: 135

Answers (1)

UPT
UPT

Reputation: 1480

Read the data into some Mutable structure (dictionary, array, string) and then append your new data into the same satring. Now write the data into the same path. So the new appended data will be written in file.

Upvotes: 2

Related Questions