我已经按照这个答案将数据写入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/