Kyle Goslan
Kyle Goslan

Reputation: 10940

Writing plist with Dictionary format

I am writing information to a plist file in the documents folder and I am around 90% of the way the way there (I think). I just need some help formatting the info I write correctly.

I need to write the data in this format:

<plist version="1.0">
<array>
<dict>
    <key>Level</key>
    <string>0</string>
    <key>Top</key>
    <string>0</string>
    <key>Needed</key>
    <string>0</string>
    <key>Passed</key>
    <string>0</string>
</dict>
<dict>
    <key>Level</key>
    <string>1</string>
    <key>Top</key>
    <string>5300</string>
    <key>Needed</key>
    <string>4000</string>
    <key>Passed</key>
    <string>Yes</string>
</dict>
</array>
</plist>

I am using this code to write to the file:

NSMutableDictionary *array = [[NSMutableDictionary alloc]init]; 
[array setObject:field1.text forKey:@"Top"];
[array writeToFile:[self dataFilePath] atomically:YES];

Which sets the key and puts in the value. But can someone help me to get it formatted correctly to look like the plist above.

Upvotes: 0

Views: 1769

Answers (3)

user523234
user523234

Reputation: 14834

Here is an sample code:

  NSMutableArray *plistArray = [[ NSMutableArray alloc] initWithContentsOfFile:[self dataFilePath]];
  NSLog(@"plistArray before additon: %@", plistArray);
  for (NSMutableDictionary *dict in plistArray)
  {
    //if you want to search for a record only otherwise remove the if statement
    if ([[dict objectForKey:@"Top"] isEqualToString:@"0"])  //this just an example, modify this per your needed
      [dict setObject:field1.text forKey:@"Top"];  //select which dictionary record to set the Top key
  }
  NSLog(@"plistArray after additon : %@", plistArray);
  [plistArray writeToFile:[self dataFilePath] atomically:YES];

Upvotes: 1

JWWalker
JWWalker

Reputation: 22717

Your code is confused... you have a variable named array, but it is declared as a dictionary. From your property list example, it looks like you want an array at the outer level, so your code should use NSArray or NSMutableArray.

Upvotes: 0

TokyoMike
TokyoMike

Reputation: 838

If you right-click on the plist file, you should be able to open it in a text editor. Can you copy-and-paste your format if you do that? Or do you mean that you have too much data to write by hand and you're trying to write it by script?

Upvotes: 0

Related Questions