如何在 ios 中的 Plist 文件中保存、检索、删除和更新我的数据?

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

How can i save, retrieve, delete & update my data in Plist file in ios?

iosplist

提问by user3631436

I am creating a iPhone app in which i get all countries name, logo & player name. I want to save that data in .plistinstead of sqliteserver. I don't know how to create a plist file in DocumentDirectoryand save the data.

我正在创建一个 iPhone 应用程序,我可以在其中获取所有国家/地区的名称、徽标和播放器名称。我想将该数据保存在.plist而不是sqlite服务器中。我不知道如何在其中创建 plist 文件DocumentDirectory并保存数据。

Please somebody suggest me how to save data in plist file.

请有人建议我如何将数据保存在 plist 文件中。

回答by S R Nayak

I am going through with screenshot and step by step. Please follow this and you will get your answer.

我正在通过屏幕截图并逐步完成。请按照此操作,您将得到答案。

First you have to create Property List through your Xcode.

首先,您必须通过 Xcode 创建属性列表。

Step:1

第1步

enter image description here

在此处输入图片说明

Step:2

第2步

enter image description here

在此处输入图片说明

Step:3

步骤:3

Save data on your save button action :

在保存按钮操作上保存数据:

   // 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

Step:4

第四步

Retrieve Data from plist File:

从 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"];

Step:5

步骤:5

Remove data from plist file:

从 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];

Step:6

步骤:6

Update your data on Update click Action:

在更新单击操作上更新您的数据:

    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];

回答by Ashok R

SWIFT 3.0

斯威夫特 3.0

Below is the code to read and write Data in .plist File.

下面是在 .plist 文件中读取和写入数据的代码。

  1. Create a data.plist file.
  2. Make sure that root object is of type 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()
    }
    
    }
    
  1. 创建一个 data.plist 文件。
  2. 确保根对象的类型为 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()
    }
    
    }
    

output:

输出:

<?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>

enter image description here

在此处输入图片说明

回答by Narendra Jagne

Operation Read, Write, update and delete plist file Xcode 11.3 with Swift 5.0

使用 Swift 5.0 读取、写入、更新和删除 plist 文件 Xcode 11.3 的操作

Add new plist file to your project enter image description here

将新的 plist 文件添加到您的项目中 在此处输入图片说明

then storage it to the folder enter image description here

然后将其存储到文件夹中 在此处输入图片说明

When you add ur plist file to your project then you need to copy to this file from your main bundle to document directory and perform the operation , here is the code of Write, update and delete plist file

当你将你的 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)
}

and finally here is read plist file here

最后这里是读取 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)
}

回答by Mr.Javed Multani

You have already created a plist. This plist will remain same in app. If you want to edit the data in this plist, add new data in plist or remove data from plist, you can't make changes in this file.

您已经创建了一个 plist。此 plist 在应用程序中将保持不变。如果要编辑此 plist 中的数据、在 plist 中添加新数据或从 plist 中删除数据,则无法在此文件中进行更改。

For this purpose you will have to store your plist in Document Directory. You can edit your plist saved in document directory.

为此,您必须将 plist 存储在文档目录中。您可以编辑保存在文档目录中的 plist。

Save plist in document directory as:

在文档目录中将 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
{ }

Retrieve data from Plist as:

从 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"];

You can edit remove, add new data as per your requirement and save the plist again to Document Directory.

您可以根据需要编辑删除、添加新数据并将 plist 再次保存到文档目录。

Ref:https://medium.com/@javedmultani16/save-and-edit-delete-data-from-plist-in-ios-debfc276a2c8

参考:https: //medium.com/@javedmultani16/save-and-edit-delete-data-from-plist-in-ios-debfc276a2c8

回答by Sunny Shah

Simple Example

简单示例

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];

回答by Anand

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);