如何在 plist 中写入数据?
Posted
技术标签:
【中文标题】如何在 plist 中写入数据?【英文标题】:How to write a data in plist? 【发布时间】:2011-10-02 18:32:37 【问题描述】:我已按照这个答案将数据写入 plist
How to write data to the plist?
但到目前为止,我的 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 的新手,因此我们将不胜感激。
【问题讨论】:
【参考方案1】:您正在尝试将文件写入您的应用程序包,但这是不可能的。将文件保存到 Documents 文件夹中。
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
path = [path stringByAppendingPathComponent:@"drinks.plist"];
pathForResource 方法只能用于读取您在 Xcode 中添加到项目中的资源。
当您想要修改应用中的 plist 时,您通常会执行以下操作: 1. 首次启动时,将应用程序包中的 Drinks.plist 复制到应用程序的 Documents 文件夹中(使用 NSFileManager)。 2. 读写时只使用Documents文件夹中的文件。
更新
这是您将如何初始化 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];
【讨论】:
非常感谢您的回复。我只是在学习 iPhone SDK,所以你能告诉我如何在第一次启动时复制它。我应该在哪里将代码复制到我的 .plist 到我的应用程序包中?我怎么知道它已被成功复制?谢谢。 我在答案中添加了一个示例。 :) @Colas 为什么?如果您想使用委托,您只需创建自己的实例,如下所述:***.com/a/16404926/499350 和文档中:developer.apple.com/library/prerelease/ios/documentation/Cocoa/…[[NSFileManager alloc] init]
应该更好,关于线程的管理。
你会把 plist 写回应用程序包吗?以上是关于如何在 plist 中写入数据?的主要内容,如果未能解决你的问题,请参考以下文章
在 BASH 中,如何使用 plist 上的默认值写入数组中的现有元素?
我们如何在 NSMutableArray 中添加带有 Image 作为对象的 NSMutableDictionary 并将这个数组写入 Plist