jkally
jkally

Reputation: 814

How to create and use my own .plist file

I have to create a .plist file manually in Xcode, then add to it some constant data (kind of a small database), several objects, each having a string and a number. Then read it in my program into an array every time the program starts. The .plist file doesn't change. I cannot find a way to create a .plist and fill it with data manually.

Upvotes: 2

Views: 6571

Answers (2)

Majster
Majster

Reputation: 3701

Well its quite easy. Since you wont be altering it you can add it as file->new->resource->plist.. Then manually enter the data the way you like.

Reading plists can be done like so:

NSURL *file = [[NSBundle mainBundle] URLForResource:@"myplist" withExtension:@"plist"]; //Lets get the file location

 NSDictionary *plistContent = [NSDictionary dictionaryWithContentsOfURL:file];

And accessing to things in the plist would be like:

NSString *playerName = [plistContent objectForKey@"player"];

Set the key name in the xcode plist editor. Note that this only works for reading. For writing to a plist you must copy it over to the documents directory of the applicaion. I can post that for you as well if you need it.

Upvotes: 8

Daij-Djan
Daij-Djan

Reputation: 50139

you use a NSMutableDictionary, give it a NSMutableArray as a child and then call writeToFile

working sample code:

    NSMutableArray *myArrayToWrite = [NSMutableArray array];
    [myArrayToWrite addObject:@"blablub"];
    [myArrayToWrite addObject:[NSNumber numberWithInt:123]];

    NSMutableDictionary *plistToWrite = [NSMutableDictionary dictionary];
    [plistToWrite setObject:myArrayToWrite forKey:@"data"]; 

    [plistToWrite writeToFile:@"/Users/Shared/TEMP.plist" atomically:NO];

    //---
    NSDictionary *plistRead = [NSDictionary dictionaryWithContentsOfFile:@"/Users/Shared/TEMP.plist"];

    NSArray *arrayRead = [plistRead objectForKey:@"data"];
    NSLog(@"%@", arrayRead);

Upvotes: 0

Related Questions