如何在plist中写入数据? [英] How to write a data in plist?

查看:96
本文介绍了如何在plist中写入数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已按照此答案将数据写入plist

I have followed this answer to write data to the plist

如何将数据写入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?

我是iPhone SDK的新手,所以任何帮助都会受到赞赏。

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

推荐答案

你正在努力写作文件到您的应用程序包,这是不可能的。改为将文件保存到Documents文件夹。

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

pathForResource方法只能用于读取您在Xcode中添加到项目中的资源。

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

以下是您在应用中修改plist时通常执行的操作:

1.将drinks.plist从应用程序包复制到第一次启动时应用程序的Documents文件夹(使用 NSFileManager

2.在阅读/写作时仅使用Documents文件夹中的文件。

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.

更新

这是初始化 drinkArray 属性的方式:

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

这篇关于如何在plist中写入数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆