Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a data in plist?

Tags:

ios

iphone

plist

I have followed this answer to write data to the plist

How to write data to the plist?

But so far my plist didn't change at all.

Here is my code :-

- (IBAction)save:(id)sender
{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"drinks" ofType:@"plist"];
    NSString *drinkName = self.name.text;
    NSString *drinkIngredients = self.ingredients.text;
    NSString *drinkDirection = self.directions.text;
    NSArray *values = [[NSArray alloc] initWithObjects:drinkDirection, drinkIngredients, drinkName, nil];
    NSArray *keys = [[NSArray alloc] initWithObjects:DIRECTIONS_KEY, INGREDIENTS_KEY, NAME_KEY, nil];
    NSDictionary *dict = [[NSDictionary alloc] initWithObjects:values forKeys:keys];
    [self.drinkArray addObject:dict];
    NSLog(@"%@", self.drinkArray);
    [self.drinkArray writeToFile:path atomically:YES];
}

Do I need to perform something extra?

I am new to iPhone SDK so any help would be appreciated.

like image 507
Varundroid Avatar asked Oct 02 '11 18:10

Varundroid


1 Answers

You are trying to write the file to your application bundle, which is not possible. Save the file to the Documents folder instead.

NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
path = [path stringByAppendingPathComponent:@"drinks.plist"];

The pathForResource method can only be used for reading the resources that you added to your project in Xcode.

Here's what you typically do when you want to modify a plist in your app:
1. Copy the drinks.plist from your application bundle to the app's Documents folder on first launch (using NSFileManager).
2. Only use the file in the Documents folder when reading/writing.

UPDATE

This is how you would initialize the drinkArray property:

NSString *destPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
destPath = [destPath stringByAppendingPathComponent:@"drinks.plist"];

// If the file doesn't exist in the Documents Folder, copy it.
NSFileManager *fileManager = [NSFileManager defaultManager];

if (![fileManager fileExistsAtPath:destPath]) {
    NSString *sourcePath = [[NSBundle mainBundle] pathForResource:@"drinks" ofType:@"plist"];
    [fileManager copyItemAtPath:sourcePath toPath:destPath error:nil];
}

// Load the Property List.
drinkArray = [[NSArray alloc] initWithContentsOfFile:destPath];
like image 82
klaussner Avatar answered Sep 21 '22 14:09

klaussner