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

Posted

技术标签:

【中文标题】如何在 ios 的 Plist 文件中保存、检索、删除和更新我的数据?【英文标题】:How can i save, retrieve, delete & update my data in Plist file in ios? 【发布时间】:2014-05-26 09:47:26 【问题描述】:

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

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

【问题讨论】:

【参考方案1】:

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

首先你必须通过你的 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

步骤:4

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

【讨论】:

真的是非常简单和完美的解决方案......它节省了我很多时间。谢谢@SR Nayak 我们非常欢迎@JAGAT。感谢您的美丽评论。 我错过了什么吗?步骤 3 中的 self.nameArr 和其他属性是什么? @SRNayak....请提供用于在 Plist 中保存、删除、更新数据的任何源代码链接 如果Plist中有嵌套字典怎么办。 ?【参考方案2】:

SWIFT 3.0

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

    创建一个 data.plist 文件。

    确保根对象是字典类型。

     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 nationAndCapitalCities = NSMutableDictionary(contentsOfFile: plistPath) 
             for (_, element) in nationAndCapitalCities.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 nationAndCapitalCities = NSMutableDictionary(contentsOfFile: plistPath)!
             nationAndCapitalCities.setValue(capitalTextField.text!, forKey: nationTextField.text!)
             nationAndCapitalCities.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>

【讨论】:

【参考方案3】:

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

将新的 plist 文件添加到您的项目中

然后将其存储到文件夹中

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

【讨论】:

【参考方案4】:

简单示例

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

【讨论】:

【参考方案5】:
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);

【讨论】:

【参考方案6】:

您已经创建了一个 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

【讨论】:

以上是关于如何在 ios 的 Plist 文件中保存、检索、删除和更新我的数据?的主要内容,如果未能解决你的问题,请参考以下文章

如何将自定义数组保存/重新加载到 plist

如何获取 INFOPLIST_FILE 名称 iOS

如何保护 ios 应用程序中的默认 plist 文件

从 plist 读取,然后将对象保存到不同的 plist iOS

将应用程序配置保存在 plist 文件中的最佳实践

iOS 7设置plist保存更新[重复]