Append A New Key-Value to a Plist Dictionary at Runtime

Discussion in 'iOS Development' started by cwe7976, Jun 6, 2009.

  1. cwe7976

    cwe7976 New Member

    Joined:
    Oct 4, 2007
    Messages:
    10
    Likes Received:
    0
    I have a plist that contains a dictionary of key-value pairs in the format of:
    Code:
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
    <dict>
    	<key>1</key>
    	<string>asdf</string>
    	<key>2</key>
    	<string>qwer</string>
    	<key>3</key>
    	<string>zxcv</string>
    </dict>
    </plist>
    
    I load this plist into a NSDictionary at runtime using:
    Code:
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"words" ofType:@"plist"];
    NSMutableDictionary plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
    
    If i want to append a new value to the actual plist file is there any way to do it w/o rewriting the whole file? (aka, remove the last 2 lines of the plist file, append the key string combo and rewrite the </dict>\n</plist>.

    Although this example plist would not take long to rewrite, mine is muuuuch longer and takes about 3/4 seconds to rewrite, which is unacceptable for only really adding 2 new lines of code each time.

    Any ideas?
  2. gojohnnyboi

    gojohnnyboi Well-Known Member

    Joined:
    Jan 25, 2008
    Messages:
    3,339
    Likes Received:
    55
    Code:
    [plistDict setObject:@"owdl" forKey:@"4"];
    [plistDict writeToFile:filePath atomically:YES];
    You do not necessarily need to rewrite the file right then if you're just using the NSDictionary, but if you want to save that data to read from the file again later, write it out to disk like above.
  3. cwe7976

    cwe7976 New Member

    Joined:
    Oct 4, 2007
    Messages:
    10
    Likes Received:
    0
    yea, but that defeats the purpose of what I am trying to do,

    I dont want the user to have to wait for the program to re-write 150,000 lines of code when it is only adding 2 lines of new info..
  4. Cyanidepoison

    Cyanidepoison Active Member

    Joined:
    Jan 18, 2008
    Messages:
    1,076
    Likes Received:
    2
    So spawn a new thread?

    Oh, and if you're pushing 150,000 lines, switch to SQLite.
  5. gojohnnyboi

    gojohnnyboi Well-Known Member

    Joined:
    Jan 25, 2008
    Messages:
    3,339
    Likes Received:
    55
    Cast that to a CFPropertyListRef, and write it in the binary plist format, which loads faster, as well as spawn a new thread for it.
  6. SkylarEC

    SkylarEC Super Moderator Emeritus Staff Member

    Joined:
    Sep 19, 2007
    Messages:
    6,642
    Likes Received:
    129
    I agree with Cyanide Poison, a property list is the wrong solution for you in this instance.

    Look into a database and/or CoreData.

Share This Page