简体   繁体   中英

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM