How do I append a new item to a plist?

你。 提交于 2019-11-29 04:52:54

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.

Brock Woolf

(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];

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];
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!