【问题标题】:Having issue with adding the string a plist file将字符串添加到 plist 文件时遇到问题
【发布时间】:2016-05-04 10:40:46
【问题描述】:

我的应用程序中有一个 plist 文件,表格视图会加载它的对象。当用户在textfield 中输入文本并点击保存按钮时,我需要保存一个字符串,这是我的代码,日志显示了正确的字符串,但表格没有重新加载,plist 没有添加任何内容!

     NSString *rootPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *plistPath=[rootPath stringByAppendingPathComponent:@"users.plist"];
NSMutableDictionary *plist_dict=[[NSMutableDictionary alloc]initWithContentsOfFile:plistPath];

if(plist_dict==nil)
{
    plist_dict =[[NSMutableDictionary alloc]init];
}
[plist_dict setObject:_username.text forKey:@"username"];

[plist_dict writeToFile:plistPath atomically:YES];


[_tableView reloadData];

这是我的默认 plist 文件:

<plist version="1.0">
<dict>
    <key>username</key>
    <array>
        <string>Instagram</string>
    </array>
</dict>
</plist>

【问题讨论】:

  • 检查并报告来自[NSArray writeToFile:atomically:] 的返回值,看看是否是问题所在。
  • @trojanfoe 你会检查我编辑的 Q 吗?
  • 我觉得之前的代码没问题;将 plist 写为数组是可以的。但是,您必须做的是检查 writeToFile: 返回的内容,并在发生故障时写入日志条目,以缩小错误的来源。
  • @trojanfoe 当我登录 plist_dict 时,它给了我正确的结果:例如 username = xxx; 但它不会刷新 tableview 并添加到 plist 文件,顺便说一下我如何检查和报告[NSArray writeToFile:atomically:] ?
  • 使用if 语句和对NSLog() 的调用。

标签: ios objective-c iphone plist


【解决方案1】:
 NSString *rootPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *plistPath=[rootPath stringByAppendingPathComponent:@"appSetting.plist"];
NSMutableDictionary *plist_dict=[[NSMutableDictionary alloc]initWithContentsOfFile:plistPath];

if(plist_dict==nil)
{
    plist_dict =[[NSMutableDictionary alloc]init];
}
[plist_dict setObject:[NSNumber numberWithBool:status] forKey:@"isLoggedIn"];

[plist_dict writeToFile:plistPath atomically:YES];

使用此代码。它为我工作。希望对你有帮助。

【讨论】:

  • 仍然没有添加任何东西!我的 plist 中没有任何 key
  • 你应该使用 key 否则将如何访问该值
  • 我只是添加了密钥,但仍然不起作用!检查我编辑的问题
猜你喜欢
  • 2013-01-15
  • 1970-01-01
  • 2014-04-24
  • 2010-12-06
  • 1970-01-01
  • 2014-12-05
  • 2014-04-12
  • 1970-01-01
  • 2017-03-10
相关资源
最近更新 更多