![](/img/trans.png)
[英]How can I save each time a new data to my plist file rather than replace the old one?
[英]How can i save, retrieve, delete & update my data in Plist file in ios?
我正在创建一个 iPhone 应用程序,我可以在其中获取所有国家/地区的名称、徽标和播放器名称。 我想将该数据保存在.plist
而不是sqlite
服务器中。 我不知道如何在DocumentDirectory
创建 plist 文件并保存数据。
请有人建议我如何将数据保存在 plist 文件中。
我正在通过屏幕截图并逐步完成。 请按照此操作,您将得到答案。
首先,您必须通过 Xcode 创建属性列表。
第1步
第2步
步骤:3
在保存按钮操作上保存数据:
// Take 3 array for save the data .....
-(IBAction)save_Action:(id)sender
{
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"manuallyData.plist"];
[self.nameArr addObject:self.nameField.text];
[self.countryArr addObject:self.countryField.text];
[self.imageArr addObject:@"image.png"];
NSDictionary *plistDict = [[NSDictionary alloc] initWithObjects: [NSArray arrayWithObjects: self.nameArr, self.countryArr, self.imageArr, nil] forKeys:[NSArray arrayWithObjects: @"Name", @"Country",@"Image", nil]];
NSError *error = nil;
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
if(plistData)
{
[plistData writeToFile:plistPath atomically:YES];
alertLbl.text = @"Data saved sucessfully";
}
else
{
alertLbl.text = @"Data not saved";
}
}
// Data is saved in your plist and plist is saved in DocumentDirectory
第四步
从 plist 文件中检索数据:
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"manuallyData.plist"];
if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath])
{
plistPath = [[NSBundle mainBundle] pathForResource:@"manuallyData" ofType:@"plist"];
}
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
self.nameArr = [dict objectForKey:@"Name"];
self.countryArr = [dict objectForKey:@"Country"];
步骤:5
从 plist 文件中删除数据:
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"manuallyData.plist"];
NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithContentsOfFile:(NSString *)plistPath];
self.nameArr = [dictionary objectForKey:@"Name"];
self.countryArr = [dictionary objectForKey:@"Country"];
[self.nameArr removeObjectAtIndex:indexPath.row];
[self.countryArr removeObjectAtIndex:indexPath.row];
[dictionary writeToFile:plistPath atomically:YES];
步骤:6
在更新单击操作上更新您的数据:
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"manuallyData.plist"];
if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath])
{
plistPath = [[NSBundle mainBundle] pathForResource:@"manuallyData" ofType:@"plist"];
}
self.plistDic = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
[[self.plistDic objectForKey:@"Name"] removeObjectAtIndex:self.indexPath];
[[self.plistDic objectForKey:@"Country"] removeObjectAtIndex:self.indexPath];
[[self.plistDic objectForKey:@"Image"] removeObjectAtIndex:self.indexPath];
[[self.plistDic objectForKey:@"Name"] insertObject:nameField.text atIndex:self.indexPath];
[[self.plistDic objectForKey:@"Country"] insertObject:countryField.text atIndex:self.indexPath];
[[self.plistDic objectForKey:@"Image"] insertObject:@"dhoni.jpg" atIndex:self.indexPath];
[self.plistDic writeToFile:plistPath atomically:YES];
斯威夫特 3.0
下面是在 .plist 文件中读取和写入数据的代码。
确保根对象的类型为 Dictionary。
class PersistanceViewControllerA: UIViewController { @IBOutlet weak var nationTextField: UITextField! @IBOutlet weak var capitalTextField: UITextField! @IBOutlet weak var textView: UITextView! override func viewDidLoad() { super.viewDidLoad() displayNationAndCapitalCityNames() //Get Path func getPath() -> String { let plistFileName = "data.plist" let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) let documentPath = paths[0] as NSString let plistPath = documentPath.appendingPathComponent(plistFileName) return plistPath } //Display Nation and Capital func displayNationAndCapitalCityNames() { let plistPath = self.getPath() self.textView.text = "" if FileManager.default.fileExists(atPath: plistPath) { if let nationAndCapitalCitys = NSMutableDictionary(contentsOfFile: plistPath) { for (_, element) in nationAndCapitalCitys.enumerated() { self.textView.text = self.textView.text + "\\(element.key) --> \\(element.value) \\n" } } } } //On Click OF Submit @IBAction func onSubmit(_ sender: UIButton) { let plistPath = self.getPath() if FileManager.default.fileExists(atPath: plistPath) { let nationAndCapitalCitys = NSMutableDictionary(contentsOfFile: plistPath)! nationAndCapitalCitys.setValue(capitalTextField.text!, forKey: nationTextField.text!) nationAndCapitalCitys.write(toFile: plistPath, atomically: true) } nationTextField.text = "" capitalTextField.text = "" displayNationAndCapitalCityNames() } }
输出:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Canada</key>
<string>Ottawa</string>
<key>China</key>
<string>Beijin</string>
<key>Germany</key>
<string>Berlin</string>
<key>United Kingdom</key>
<string>London</string>
<key>United States of America</key>
<string>Washington, D.C.</string>
</dict>
</plist>
使用 Swift 5.0 读取、写入、更新和删除 plist 文件 Xcode 11.3 的操作
当你将你的 plist 文件添加到你的项目中时,你需要从你的主包复制到这个文件到文档目录并执行操作,这里是写入、更新和删除 plist 文件的代码
//Operation Write, update and delete plist file
static func chipsOperationPropertyList(operation: chipsOperation) {
//chipOperation is enum for add, edit and update
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let path = paths.appending("/StoreData.plist")
let fileManager = FileManager.default
if (!(fileManager.fileExists(atPath: path)))
{
do {
let bundlePath : NSString = Bundle.main.path(forResource: "StoreData", ofType: "plist")! as NSString
try fileManager.copyItem(atPath: bundlePath as String, toPath: path)
}catch {
print(error)
}
}
var plistDict:NSMutableDictionary = NSMutableDictionary(contentsOfFile: path)!
switch operation {
case chipsOperation.add:
plistDict.setValue("Value", forKey: "Key")
break
case chipsOperation.edit:
plistDict["Key"] = "Value1"
break
case chipsOperation.delete:
plistDict.removeObject(forKey: "Key")
break
}
plistDict.write(toFile: path, atomically: true)
}
最后这里是读取 plist 文件
static func readPropertyList() {
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let path = paths.appending("/StoreData.plist")
let plistDict = NSDictionary(contentsOfFile: path)
print(plistDict)
}
简单示例
NSString *filePath=[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"country.plist"];
// ADD Plist File
NSMutableArray *arr=[[NSMutableArray alloc]initWithObjects:@"India",@"USA" ,nil];
[arr writeToFile:filePath atomically:YES];
//Update
NSFileManager *fm=[NSFileManager defaultManager];
[arr removeObjectIdenticalTo:@"India"];
[fm removeItemAtPath:filePath error:nil];
[arr writeToFile:filePath atomically:YES];
// Read
NSMutableArray *arr=[[NSMutableArray alloc]initWithContentsOfFile:filePath];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"plist.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: path]) {
path = [documentsDirectory stringByAppendingPathComponent: [NSString stringWithFormat: @"yourfilename.plist"]];
}
NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSMutableDictionary *data;
if ([fileManager fileExistsAtPath: path]) {
data = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
} else {
// If the file doesn’t exist, create an empty dictionary
data = [[NSMutableDictionary alloc] init];
}
//To insert the data into the plist
int value = 5;
[data setObject:[NSNumber numberWithInt:value] forKey:@"value"];
[data writeToFile: path atomically:YES];
//To retrieve the data from the plist
NSMutableDictionary *savedStock = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
int savedvalue;
savedvalue = [[savedStock objectForKey:@"value"] intValue];
NSLog(@“%d”, savedvalue);
您已经创建了一个 plist。 此 plist 在应用程序中将保持不变。 如果要编辑此 plist 中的数据、在 plist 中添加新数据或从 plist 中删除数据,则无法在此文件中进行更改。
为此,您必须将 plist 存储在文档目录中。 您可以编辑保存在文档目录中的 plist。
在文档目录中将 plist 保存为:
NSString *filePath = [[NSBundle mainBundle] pathForResource:@”Data” ofType:@”plist”]; NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:filePath]; NSDictionary *plistDict = dict;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *error = nil;
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict
format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
if (![fileManager fileExistsAtPath: plistPath]) {
if(plistData)
{
[plistData writeToFile:plistPath atomically:YES];
}
}
else
{ }
从 Plist 检索数据为:
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask,
YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"Data.plist"];
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
NSArray *usersArray = [dict objectForKey:@"Object1"];
您可以根据需要编辑删除、添加新数据并将 plist 再次保存到文档目录。
参考: https : //medium.com/@javedmultani16/save-and-edit-delete-data-from-plist-in-ios-debfc276a2c8
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.