0

Can anyone please tell me how to write NSMutableArray of custom class objects to file? below is the code which i am using to write my array "medicationsArray" to file. medicationsArray contains the objects of below medicationData class

@interface medicationData: NSObject { NSString *drName; NSString *date; NSString *description; } @end

NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentDir = [path objectAtIndex:0];
NSString *pathWithFileName;

NSString *pathWithFileName = [NSString stringWithFormat:@"%@/medicationsArray",documentDir];
[medicationsArray writeToFile:pathWithFileName atomically:NO];

by using this code i am not able to create a file. can anyone help me in this, thanks in advance

1
  • So, your medicationsArray contains medicationData, right? Commented Jun 12, 2010 at 9:19

2 Answers 2

2

Instead of constructing the pathWithFileName "manually" you should use the stringByAppendingPathComponent: method instead:

NSString *pathWithFileName = [documentDir stringByAppendingPathComponent:@"medicationsArray"];

This will take care of any extra slashes, etc. in the path. This might be the reason your path may be wrong. I presume that the extra declaration of pathWithFileName in your snippet is just a typo.

Sign up to request clarification or add additional context in comments.

Comments

0

Thank you for the reply Claus, Now i am able to store the data, i am using NSArchiver and NSUnArchiver. below is the code please find.

NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentDir = [path objectAtIndex:0];
NSString *pathWithFileName;

pathWithFileName = [NSString stringWithFormat:@"%@/medicationsArray",documentDir];
NSData *savedData = [NSKeyedArchiver archivedDataWithRootObject:appDelegate.medicationsArray];
[savedData writeToFile:pathWithFileName atomically:YES];

to extract the data

if([[NSFileManager defaultManager] fileExistsAtPath:pathWithFileName])
{
    NSData *savedData = [[NSData dataWithContentsOfFile:pathWithFileName] retain];
    appDelegate.medicationsArray = [[NSKeyedUnarchiver unarchiveObjectWithData:savedData] retain];
    [objMedicationDetailsTVController.tableView reloadData];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.