Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I append a new item to a plist?

In my iPhone app, I have two plist files to store "Themes". One is a read-only file containing default themes, and one contains custom Themes that the user has created. I'm using plist files because it's very easy for me to read from the plist and create new Theme objects.

My plist is an array of dictionary objects.

Is there any easy way to append a new dictionary object to my plist file? Or do I need to read the file into memory, append the new dictionary object, and write it back to the filesystem?

Thanks!

like image 534
Reed Olsen Avatar asked Oct 19 '09 01:10

Reed Olsen


People also ask

How do I create a new plist?

To create a plist file, it just as simple as creating a new class. Click menu File > New > File... ( ⌘ - CMD + N ).)


2 Answers

With Cocoa, you need to read the file into memory, append the new dictionary object, and write it back to the filesystem. If you use an XML plist, you could pretty easily parse it and incrementally write to the file, but it'd also be quite a bit bigger, so it's unlikely to be worth it.

If rewriting the plist is taking too long, you should investigate using a database instead (perhaps via Core Data). Unless the file is huge, I doubt this will be an issue even with the iPhone's memory capacity and flash write speed.

like image 188
Nicholas Riley Avatar answered Nov 15 '22 07:11

Nicholas Riley


(I copied this for those who don't want to click a link from a similar question I answered here: A question on how to Get data from plist & how should it be layout)

Here are two methods to read and write values from a plist using an NSDictionary:

- (NSMutableDictionary*)dictionaryFromPlist {
    NSString *filePath = @"myPlist.plist";
    NSMutableDictionary* propertyListValues = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
    return [propertyListValues autorelease];
}

- (BOOL)writeDictionaryToPlist:(NSDictionary*)plistDict{
    NSString *filePath = @"myPlist.plist";
    BOOL result = [plistDict writeToFile:filePath atomically:YES];
    return result;
}

and then in your code block somewhere:

// Read key from plist dictionary
NSDictionary *dict = [self dictionaryFromPlist];
NSString *valueToPrint = [dict objectForKey:@"Executable file"];
NSLog(@"valueToPrint: %@", valueToPrint);

// Write key to plist dictionary
NSString *key = @"Icon File";
NSString *value = @"appIcon.png";
[dict setValue:value forKey:key];

// Write new plist to file using dictionary
[self writeDictionaryToPlist:dict];
like image 35
Brock Woolf Avatar answered Nov 15 '22 05:11

Brock Woolf