微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ios – 如何用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文件夹中的文件.

UPDATE

这是初始化drinkArray属性方法

Nsstring *destPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,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];

原文地址:https://www.jb51.cc/iOS/333396.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐