Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone read/write .plist file

I'm making a application where I need to store some information the user have provided. I try to use a .plist file to store the information, I found this:

NSString *filePath = @"/Users/Denis/Documents/Xcode/iPhone/MLBB/data.plist";
NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
[plistDict setValue:@"Man" forKey:@"Gender"];
[plistDict writeToFile:filePath atomically: YES];

The problem is that the application will only work as long as I'm testing it in the iPhone simulator. I've tried this Changing Data in a Plist but without luck. I have also read something about that I need to add it to my bundle, but how?

New code:

- (IBAction)segmentControlChanged{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *plistLocation = [documentsDirectory stringByAppendingPathComponent:@"data.plist"];
NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:plistLocation];

if (Gender.selectedSegmentIndex == 0) {
    [plistDict setObject:@"Man" forKey:@"Gender"];
    [plistDict writeToFile:plistLocation atomically: YES];
}
else
{
    [plistDict setObject:@"Women" forKey:@"Gender"];
    [plistDict writeToFile:plistLocation atomically: YES];
}
}
like image 283
Deni Avatar asked Feb 17 '12 21:02

Deni


People also ask

What is a plist file on Iphone?

plist file contains critical information about the configuration of an iOS mobile app—such as iOS versions that are supported and device compatibility—which the operating system uses to interact with the app. This file is automatically created when the mobile app is compiled.

What are Apple plist files?

Plist files are Mac files that allow you to save preferences in the apps you use. Occasionally they may need to be deleted to restore proper functionality to a program experiencing a conflict. You'll want to follow these steps when another article or situation calls for deleting your . plist file.

Where are plist files on Iphone?

plist file contains the preferences for the TextEdit application (located in ~/Library/Containers/com. apple. TextEdit/Data/Library/Preferences/ ).

How do I read a plist file in Swiftui?

Property lists are perfect for saving simple, static key-value data in your app. Here's how you can read a plist with Swift: func getPlist(withName name: String) -> [String]?

What is property list file?

A property list file is a settings file: a file containing properties related to a specific application in a structured data format. Such properties include names of an app executable file, identifiers of the app bundle type and more. Two of the most important tools used to edit and parse .


1 Answers

I guess you have added your plist file to your resources folder in Xcode (where we place image, if not then you need to place that first). Resources data goes to [NSBundle mainBundle] by default and iOS does not allow us to change data inside bundle. So first you need to copy that file to Documents Directory.

Here is the code for copying file from NSBundle to the Documents directory.

- (NSString *)copyFileToDocumentDirectory:(NSString *)fileName {
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                         NSUserDomainMask,
                                                         YES);
    NSString *documentsDir = [paths objectAtIndex:0];
    NSString *documentDirPath = [documentsDir
                                      stringByAppendingPathComponent:fileName];

    NSArray *file = [fileName componentsSeparatedByString:@"."];
    NSString *filePath = [[NSBundle mainBundle]
                                         pathForResource:[file objectAtIndex:0]
                                                  ofType:[file lastObject]];

    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL success = [fileManager fileExistsAtPath:documentDirPath];

    if (!success) {
        success = [fileManager copyItemAtPath:filePath
                                       toPath:documentDirPath
                                        error:&error];
        if (!success) {
        NSAssert1(0, @"Failed to create writable txt file file with message \
                                         '%@'.", [error localizedDescription]);
        }
    }

    return documentDirPath;
}

Now you can use the returned documentDirPath to access that file and manipulate (Read/Write) over that.

The plist structure is:

<array>
    <dict>key-value data</dict>
    <dict>key-value data</dict>
</array>

Here is code to write data into plist file:

/* Code to write into file */

- (void)addToMyPlist {
    // set file manager object
    NSFileManager *manager = [NSFileManager defaultManager];

    // check if file exists
    NSString *plistPath = [self copyFileToDocumentDirectory:
                                                       @"MyPlistFile.plist"];

    BOOL isExist = [manager fileExistsAtPath:plistPath];    
    // BOOL done = NO;

    if (!isExist) {
        // NSLog(@"MyPlistFile.plist does not exist");
        // done = [manager copyItemAtPath:file toPath:fileName error:&error];
    }
    // NSLog(@"done: %d",done);

    // get data from plist file
    NSMutableArray * plistArray = [[NSMutableArray alloc]
                                           initWithContentsOfFile:plistPath];

    // create dictionary using array data and bookmarkKeysArray keys
    NSArray *keysArray = [[NSArray alloc] initWithObjects:@"StudentNo", nil];
    NSArray *valuesArray = [[NSArray alloc] initWithObjects:
                                   [NSString stringWithFormat:@"1234"], nil];

    NSDictionary plistDict = [[NSDictionary alloc]
                                                  initWithObjects:valuesArray
                                                          forKeys:keysArray];

    [plistArray insertObject:poDict atIndex:0];

    // write data to  plist file
    //BOOL isWritten = [plistArray writeToFile:plistPath atomically:YES];
    [plistArray writeToFile:plistPath atomically:YES];

    plistArray = nil;

    // check for status
    // NSLog(@" \n  written == %d",isWritten);
}
like image 117
Mrunal Avatar answered Oct 10 '22 11:10

Mrunal