简体   繁体   English

如何在plist中写入数据?

[英]How to write a data in plist?

I have followed this answer to write data to the plist 我已经按照这个答案将数据写入plist

How to write data to the plist? 如何将数据写入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. 我是iPhone SDK的新手,所以将不胜感激。

You are trying to write the file to your application bundle, which is not possible. 您试图将文件写入应用程序捆绑包,这是不可能的。 Save the file to the Documents folder instead. 而是将文件保存到Documents文件夹。

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. pathForResource方法只能用于读取在Xcode中添加到项目中的资源。

Here's what you typically do when you want to modify a plist in your app: 当您要在应用中修改plist时,通常会执行以下操作:
1. Copy the drinks.plist from your application bundle to the app's Documents folder on first launch (using NSFileManager ). 1.在首次启动时(使用NSFileManager )将Drinks.plist从应用程序捆绑包复制到应用程序的Documents文件夹中。
2. Only use the file in the Documents folder when reading/writing. 2.读/写时仅使用Documents文件夹中的文件。

UPDATE 更新

This is how you would initialize the drinkArray property: 这是如何初始化DrinkArray属性的方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM