views:

750

answers:

3

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!

+3  A: 

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.

Nicholas Riley
That will do! Thanks.
Reed Olsen
Just remember that you can't write to the app bundle. You have to find your app's documents directory (use `NSSearchPathForDirectoriesInDomain()`)and write it there.
Dave DeLong
A: 

(I copied this for those who don't want to click a link from a similar question I answered here: http://stackoverflow.com/questions/1605310/1617071#1617071)

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];
Brock Woolf
+1  A: 

This is how I am appending data to the plist:

    NSString *filePath = [self dataFilePath];
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) 
{
    NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:filePath];
    [array addObject:countdownLabel.text];
    [array writeToFile:[self dataFilePath] atomically:YES];
    [array release];
}
else
{
    NSArray *array = [NSArray arrayWithObject:countdownLabel.text];
    [array writeToFile:filePath atomically:YES];
}
Vibhor Goyal