2011-10-02 64 views
7

我按照这个答案将数据写入到plist中如何在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,所以任何帮助,将不胜感激。

回答

35

您正试图将文件写入您的应用程序包,这是不可能的。改为将文件保存到“文档”文件夹中。

NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; 
path = [path stringByAppendingPathComponent:@"drinks.plist"]; 

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

下面是当你想在你的应用程序修改的plist你通常做的:
1.复制(使用NSFileManager)从您的应用程序包的应用程序的文件第一次启动文件夹中的drinks.plist。
2.读/写时只能使用Documents文件夹中的文件。

UPDATE

这是你将如何初始化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]; 
+0

非常感谢您的回复。我刚刚学习iPhone SDK,因此请您在第一次发布时告诉我如何复制它。我应该在哪里将代码复制到我的应用程序包中?以及我如何知道它已被成功复制?谢谢。 – Varundroid

+3

我已经给我的答案添加了一个示例。 :) – chrisklaussner

+0

非常感谢ChristianK。 :) – Varundroid