ios - 如何在plist中写入数据?

标签 ios iphone 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 的新手,如有任何帮助,我们将不胜感激。

最佳答案

您正在尝试将文件写入您的应用程序包,这是不可能的。而是将文件保存到 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];

关于ios - 如何在plist中写入数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7628372/

相关文章:

ios - 在 UISearchBar 中设置取消按钮的样式

ios - 方向的 Swift 2 语法错误.Forward

iphone - 使用核心图形 : bubbles are shown 绘制线条时出现问题

iphone - 如何强制更新应用程序设置包?

iOS 应用程序 - 复杂的 UI 与复杂的数据分离

ios - 如何从警报的文本字段中获取文本并将其设置为单元格的文本标签?

ios - 本地化多个 Storyboard

ios - 如何使用 AFNetworking 下载多张图片?

iPhone:更改来自 NIB 的 UITableViewCell 的高度

swift - 将数据从 plist 传递到 DetailView