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

时间:2014-05-26 09:47:26

标签: ios plist

我正在创建一个iPhone应用程序,其中我获得所有国家/地区名称,徽标和&选手姓名。我想将这些数据保存在.plist而不是sqlite服务器中。我不知道如何在DocumentDirectory中创建一个plist文件并保存数据。

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

7 个答案:

答案 0 :(得分:41)

我正在浏览屏幕截图并逐步完成。请按照这个,你会得到答案。

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

<强>步骤:1

enter image description here

<强>步骤:2

enter image description here

<强>步骤: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];

答案 1 :(得分:7)

  

SWIFT 3.0

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

  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()
    }
    
    }
    
  3. 输出:

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

答案 2 :(得分:4)

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

将新的plist文件添加到您的项目 enter image description here

然后将其存储到文件夹 enter image description here

当您将ur plist文件添加到项目时,您需要从主捆绑包复制到此文件到文档目录并执行操作,这是Write,更新和删除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)
}

答案 3 :(得分:0)

简单示例

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

答案 4 :(得分:0)

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

答案 5 :(得分:0)

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

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

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

\\Save plist in document directory as:




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:



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

答案 6 :(得分:0)

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

为此,您必须将plist存储在Document Directory中。您可以编辑保存在文档目录中的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