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

6

20

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

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

Engrave answered 26/5, 2014 at 9:47 Comment(0)
F
48

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.

Step:1

enter image description here

Step:2

enter image description here

Step: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:

    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

Remove data from plist file:

    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

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];
Fadden answered 26/5, 2014 at 10:21 Comment(6)
Really it is very easy and perfect solution...It is save my lots of time. Thank You @S R NayakIntussuscept
U r most welcome @JAGAT. Thanks for ur beautiful comment.Fadden
Am I missing something? What is self.nameArr and the other properties in step 3?Dennie
@SRNayak....Please provide any Source Code Link for Saving, Deleting , Updating Data in PlistGermany
What if there are nested dictionaries in Plist. ?Amann
Assumed that dataFromPropertyList:format:errorDescription: is deprecated writing data I have this error [NSDictionary initWithObjects:forKeys:]: count of objects (0) differs from count of keys (3) why?Irruption
P
10

SWIFT 3.0

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

  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 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()
     }
    
     }
    

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

Paintbrush answered 29/10, 2016 at 10:45 Comment(0)
I
4

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

Add new plist file to your project enter image description here

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

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

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)
}
Immix answered 24/3, 2020 at 10:16 Comment(0)
C
1

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];
Cannonball answered 26/5, 2014 at 9:54 Comment(0)
M
1
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);
Motherland answered 26/5, 2014 at 9:59 Comment(0)
E
1

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.

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

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

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

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

Econometrics answered 24/8, 2019 at 22:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.