xcode 编辑 plist 中的现有数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13009768/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 01:53:38  来源:igfitidea点击:

Edit an existing data in plist

iosxcodeplist

提问by Vamsi

How can i override an existing data in a plist after checking if the data is already present or not, through coding

在检查数据是否已经存在后,如何通过编码覆盖 plist 中的现有数据

In Detail:

详细:

I am saving username and password in my plist file located in document directory. Now if user selects an change password option, the plist should check if his username exists or not. if it exists then the new password that he is entering should override the existing password in the plist.

我将用户名和密码保存在位于文档目录的 plist 文件中。现在,如果用户选择更改密码选项,plist 应该检查他的用户名是否存在。如果存在,那么他输入的新密码应该覆盖 plist 中的现有密码。

can anyone help me with some piece of sample code

谁能帮我一些示例代码

回答by Midhun MP

You can't change the plist stored in the application bundle. If you need to edit the user data stored in the plist, then you need to create the plist on the document directory.

您无法更改存储在应用程序包中的 plist。如果需要编辑存储在 plist 中的用户数据,则需要在文档目录中创建 plist。

Another option is NSUserDefaults. If there is huge data then I'll suggest sqlite3database, else you can use plistor NSUserDefaults.

另一种选择是NSUserDefaults。如果有大量数据,那么我会建议使用sqlite3数据库,否则您可以使用plistNSUserDefaults

You can alter the value of your plist like:

您可以更改 plist 的值,例如:

NSString *path = //your plist path in document directory;
NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
NSString *userExist = [plistDict objectForKey:@"UserName"]; //test the user exist
if([userExist isEqualToString:@"Midhun"])                   //checking user exist or not
{
  NSString *userPwd = @"Midhun";
  [tempDict setObject:userPwd forKey:@"PassWord"]; //Password is your key
  [tempDict writeToFile:path atomically:YES];
}

Please refer this linkfor more. Here is a plist tutorialfor you.

请参阅此链接了解更多信息。这是一个 plist教程给你。

回答by kidsid49

You can't edit a data in plist if it is in your bundle directory. Files that are present inside the bundle have "read only" permission. While if your plist reside inside the document directory then you can edit it by using following steps. (1)Get the data from plist. (2)Update it. (3)Write back the updated data to plist.

如果 plist 位于您的包目录中,则您无法编辑该数据。捆绑包内的文件具有“只读”权限。而如果您的 plist 驻留在文档目录中,那么您可以使用以下步骤对其进行编辑。(1)从plist中获取数据。(2)更新。(3)将更新后的数据写回plist。

NSString *path= [[NSBundle mainBundle] pathForResource:@"fileName" ofType:@"plist"];

if(path)

 NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];

//Update the respective dictionary dict here.

//write back to plist.

[dict writeTofile:path atomically:YES];