How to write a data in plist?

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];

Leave a Comment