xcode 在 plist 中添加和删除数组项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10995155/
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 00:34:41  来源:igfitidea点击:

Add & Remove Array Items inside a plist

iphoneobjective-cxcodeplist

提问by danialmoghaddam

I have problem with adding and removing items in an array inside a plist file in XCODE.

我在 XCODE 的 plist 文件中添加和删除数组中的项目时遇到问题。

I'm able to read the array by following code:

我可以通过以下代码读取数组:

// Path to the plist (in the application bundle) ------>>>>>
NSString *path = [[NSBundle mainBundle] pathForResource:
                  @"Fav" ofType:@"plist"];

// Build the array from the plist  ------>>>

NSDictionary *favs = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
Resepies = [favs objectForKey:@"Root"];

And this my plist structure

这是我的 plist 结构

enter image description here

在此处输入图片说明

The senario is to let the user add and remove specific item from the array at a time.

方案是让用户一次从数组中添加和删除特定项目。

回答by Abhishek

try this code -

试试这个代码 -

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

// Build the array from the plist  ------>>>

NSDictionary *favs = [[NSMutableDictionary alloc] initWithContentsOfFile: path];

Resepies = [favs objectForKey:@"Root"];

[Resepies addObject:addYourObjectHere];

//then add this array into dictonary ; 

[favs setObject:Resepies forKey:@"Root"];

// now write dictionary to plist

[favs writeToFile:yourPlistName atomically:YES];

回答by Paresh Navadiya

You can't modify files in the application bundle, which is what your code above is attempting to do.

您无法修改应用程序包中的文件,这正是您上面的代码试图执行的操作。

If the file is supposed to be modifiable, you need to move it into the documents folder first (say, on first run) and then read / write to that one subsequently. There are plenty of questions dealing with how to do this, for example : createplist and copying plist to document directory

如果该文件应该是可修改的,则需要先将其移动到文档文件夹中(例如,在第一次运行时),然后随后读取/写入该文件夹。有很多问题涉及如何执行此操作,例如:创建plist 并将 plist 复制到文档目录