如何在plist中写入数据?
我已按照此答案将数据写入 plist
How to write data to the plist?< /a>
但到目前为止我的 plist 根本没有改变。
这是我的代码:-
- (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];
}
我需要执行额外的操作吗?
我是 iPhone SDK 的新手,因此我们将不胜感激。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在尝试将该文件写入应用程序包,但这是不可能的。将文件保存到“文档”文件夹中。
pathForResource 方法只能用于读取您在 Xcode 中添加到项目中的资源。
当您想要修改应用程序中的 plist 时,您通常会执行以下操作:
1. 在首次启动时将 Drinks.plist 从应用程序包复制到应用程序的 Documents 文件夹(使用 NSFileManager)。
2. 读/写时仅使用Documents 文件夹中的文件。
更新
这是初始化drinkArray属性的方法:
You are trying to write the file to your application bundle, which is not possible. Save the file to the Documents folder instead.
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: